VBA Examples – Getting username and computer name from system

Declare PtrSafe Function GetUserName Lib “advapi32.dll” Alias “GetUserNameA” (ByVal lpBuffer As String, nSize As Long) As Long
Declare PtrSafe Function GetComputerName Lib “kernel32” Alias “GetComputerNameA” (ByVal lpBuffer As String, nSize As Long) As Long

Public Function SystemUser() As String

Dim sUser As String
Dim sComputer As String
Dim lpBuff As String * 1024

‘Get the Login User Name
GetUserName lpBuff, Len(lpBuff)
sUser = VBA.Left$(lpBuff, (InStr(1, lpBuff, vbNullChar)) – 1)
lpBuff = “”

‘Get the Computer Name
GetComputerName lpBuff, Len(lpBuff)
sComputer = VBA.Left$(lpBuff, (InStr(1, lpBuff, vbNullChar)) – 1)
lpBuff = “”
SystemUser = sUser

‘ MsgBox “Login User: ” & sUser & vbCrLf & _
“Computer Name: ” & sComputer

End Function

Leave a Reply