Re: Get system username ...
You can use the environmental variables...
VB Code:
Dim strUser
strUser = Environ("Username")
MsgBox strUser
Re: Get system username ...
this is what I would use in VB. Should be the same for VBA?
VB Code:
'API declaration at top of module
Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
'function for getting logged in system username
Private Function GetCurrentNTUserName() As String
On Error GoTo Err_Handler
Dim llReturn As Long
Dim lsUserName As String
Dim lsBuffer As String
lsUserName = ""
lsBuffer = Space$(255)
llReturn = GetUserName(lsBuffer, 255)
If llReturn Then
lsUserName = Left$(lsBuffer, InStr(lsBuffer, vbNullChar) - 1)
End If
GetCurrentNTUserName = lsUserName
Exit Function
Err_Handler:
GetCurrentNTUserName = vbNullString
End Sub
Re: Get system username ...
Quote:
Originally Posted by dannymking
You can use the environmental variables...
VB Code:
Dim strUser
strUser = Environ("Username")
MsgBox strUser
I don't believe it! All these years I've used the API to get it and it was that simple all along :blush: :blush:
Re: Get system username ...
Blade,
I used to use that too... But then the environment variables saved a lot of code :D
Re: Get system username ...
There's a whole list of them.. and this works in VBA, VB6.0 and VB.Net
Re: Get system username ...
I'm going to have to have a nosey round I think.
Don't suppose there's one in there for computer name as well? (another one which I'm currently using the API for)
Re: Get system username ...
tsk... it's all so simple (COMPUTERNAME) :s
just found this bit of code for listing the environ variables
VB Code:
Private Sub Form_Load()
'Set form autoredraw property to true to get this example
'to work
Dim myuser As Variant
Dim I As Integer
'used to test if any environment variables exist
'sometimes they don't
Dim sTemp As String
I = 1
myuser = Environ(I)
sTemp = myuser
Form1.Print Environ(I)
I = I + 1
'Print all values on form
Do While Len(myuser) > 0
Form1.Print Environ(I)
I = I + 1
myuser = Environ(I)
sTemp = sTemp & myuser
Loop
If Len(sTemp) = 0 Then Form1.Print _
"No environment variables exist"
End Sub
Re: Get system username ...
Thanks a lot - PERFECT answer
Have a nice weekend
Re: Get system username ...
I think there are a total of 34 of these.. At least on Vista there is
Re: Get system username ...
Be careful when relying upon the environment variables as these can be deleted and/or changed from what is accurate. I always recommend the APIs for getting either computer name and user name. ;)
Time taken to post - 30 seconds.
Not having to work out issues from users changing environment variables - priceless. :D