By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,836 Members | 2,055 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Function to return Username (NT Login) of current user

Expert Mod 10K+
P: 14,534
This function returns the username of the currently logged in NT User.

Expand|Select|Wrap|Line Numbers
  1. ' This library must be declared
  2. Declare Function GetUserName& _
  3.                      Lib "advapi32.dll" Alias _
  4.                      "GetUserNameA" (ByVal lpBuffer As String,
  5.                                      nSize As Long)
  7. Function sys_OrigUserID() As String
  8. Dim s$, cnt&, dl&
  9. Dim max_String As Integer
  10. Dim username As String
  12.     max_String = 30
  13.     cnt& = 199
  14.     s$ = String$(max_String, 1)
  15.     dl& = GetUserName(s$, cnt)
  16.     username = Trim$(Left$(s$, cnt))
  17.     username = UCase(Mid(username, 1, Len(username) - 1))
  18.     sys_OrigUserID = username
  20. End Function
May 29 '07 #1
Share this Article
Share on Google+

Expert 2.5K+
P: 3,072
As an alternative you can use the Environ() function like:
Expand|Select|Wrap|Line Numbers
  1. strUser = Environ("username")
This Environ() function can be used to extract all system variables like the computername, etc. as long as the variable has been defined and has been filled.

To get all available variables you can open the cmd window (Start / Run.. and enter the string "cmd") now by typing SET after the "C:>" prompt and pressing [Enter] all available variables (including the "username") will show and all of these can be extracted with this Environ() function. Keep however in mind that not all variables will be available on all computers...

May 29 '07 #2

Expert Mod 15k+
P: 31,306
Bear in mind also that the Environ() function will return whatever is in the Environment Variable "USERNAME". While this is set up with the username, there's nothing to stop it being changed within a session. If you're using this as part of a security feature then it's best to use GetUserName().
Nov 20 '07 #3