userID

G

Gonzo

I would like to offer a user different resources based on a windows login -
xp and win 2000.

Does VBA have a way to find out the local machine logon account name?
 
M

Mark Tangard

Hi Gonzo,

This is from notes I made here when I just a pup. I have no idea
what most of it means or (sorry) who posted it, but it does work:
(If someone recognizes this as his/her code, please let me know
so it can be properly attributed now and later.)

GET NETWORK LOGIN USERNAME:

' Declare for call to mpr.dll.
Declare Function WNetGetUser Lib "mpr.dll" _
Alias "WNetGetUserA" (ByVal lpName As String, _
ByVal lpUserName As String, lpnLength As Long) As Long

Const NoError = 0 'The Function call was successful

Sub GetUserName()

' Buffer size for the return string.
Const lpnLength As Integer = 255

' Get return buffer space.
Dim status As Integer

' For getting user information.
Dim lpName, lpUserName As String

' Assign the buffer size constant to lpUserName.
lpUserName = Space$(lpnLength + 1)

' Get the log-on name of the person using product.
status = WNetGetUser(lpName, lpUserName, lpnLength)

' See whether error occurred.
If status = NoError Then
' This line removes the null character. Strings in C are null-
' terminated. Strings in Visual Basic are not null-terminated.
' The null character must be removed from the C strings to be used
' cleanly in Visual Basic.
lpUserName = Left$(lpUserName, InStr(lpUserName, Chr(0)) - 1)
Else

' An error occurred.
MsgBox "Unable to get the name."
End
End If

' Display the name of the person logged on to the machine.
MsgBox "The person logged on this machine is: " & lpUserName

End Sub
 
J

Jay Freedman

Mark said:
Hi Gonzo,

This is from notes I made here when I just a pup. I have no idea
what most of it means or (sorry) who posted it, but it does work:
(If someone recognizes this as his/her code, please let me know
so it can be properly attributed now and later.)
It's on the MVPs site at
http://www.mvps.org/word/FAQs/MacrosVBA/GetCurUserName.htm, where Astrid
attributed it to a KnowledgeBase article.

While that code, based on an API function, should work for all Windows
versions, you may be lucky enoough to be able to use Environ("username") as
a quick way to get the string.
 
G

Gonzo

I guess is should have specified "easy way to ...."
Jay - thanks again- it works great in my win XP pro environment and by
golly it's pretty efficient.

Thanks also Mark, but man I got a migraine just trying to read the API
version. Guess I better break down and get Dan Appleman's book on VBA and
the win API.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top