Getting Windows user name

There is not much to write about it. Short code to get Windows user name. Quite interesting is declaration for 32bit and 64bit systems. Unfortunately I’ve forgot source of code.

'  Declaration for 32bit and 64bit systems
#If VBA7 Then
    Declare PtrSafe Function Get_User_Name Lib "advapi32.dll" Alias _
    "GetUserNameA" (ByVal lpBuffer As String, _
    nSize As Long) As LongPtr
#Else
    Declare Function Get_User_Name Lib "advapi32.dll" Alias _
    "GetUserNameA" (ByVal lpBuffer As String, _
    nSize As Long) As Long
#End If

Sub UserName()
' Run this macro first

MsgBox GetUserName
End Sub

Function GetUserName() As String
' This is used by GetUserName() to find the current user's
' name from the API

Dim lpBuff As String * 25

Get_User_Name lpBuff, 25
GetUserName = Left(lpBuff, InStr(lpBuff, Chr(0)) - 1)
End Function

Leave a Reply

Your email address will not be published. Required fields are marked *