Just to make things simple, there are two ways to get the system logon username.
1. Using the environment variable. This is straightforward and should work for most cases.
2. Using API.
In both cases, the messagebox returns my logon name:
gerry.knight
Gerry
1. Using the environment variable. This is straightforward and should work for most cases.
Code:
Sub GetNameUsingEnviron()
MsgBox Environ("username")
End Sub
2. Using API.
Code:
Option Explicit
[COLOR=red]' the API function[/color red]
Private Declare Function GetUserName Lib "advapi32.dll" _
Alias "GetUserNameA" _
(ByVal lpBuffer As String, _
nSize As Long) As Long
[COLOR=red]' the API-using function[/color red]
Function GetName() As String
Dim lpBuffer As String
Dim nSize As Long
[COLOR=red]' initialize buffer[/color red]
nSize = 255
lpBuffer = Space$(nSize)
[COLOR=red]' get the name[/color red]
If GetUserName(lpBuffer, nSize) Then
[COLOR=red] ' return the username
' remembering API returns an extra character[/color red]
GetName = Left$(lpBuffer, nSize - 1)
Else
GetName = ""
End If
End Function
[COLOR=red]' the Sub to use the API-using function[/color red]
Sub GetNameUsingAPI()
MsgBox GetName
End Sub
In both cases, the messagebox returns my logon name:
gerry.knight
Gerry