Using VBA To Find Current User Name

Sometimes it can be useful to know which user is logged on to your application, maybe in order to check that they have the correct permission to use the application etc, or maybe unlock certain features that are only available to certain users.

We have outlined some code below to help you achieve this, the code is universal, and has been tested in Word, Excel, Access, and PowerPoint

In the VBA Editor, create a new module and paste in the following code:

Private Declare Function GetUserName Lib “advapi32.dll” Alias “GetUserNameA” (ByVal _ lpBuffer As String, nSize As Long) As Long
Function UserName() As String
Dim Stack As String *100
Dim StackLength As Long
StackLength = 100
GetUserName Stack, StackLength
UserName = Left(Stack, StackLength – 1)
End Function

Now you can call the function ‘UserName’ at anytime in the program and you will returned with the name of the currently logged in user.

An example would be this piece of code that finds the username, assigns it to a variable named ‘Person’ and then displays it in a message box.

Dim Person As String
Person = UserName()
MsgBox (Person)

In the example above, assigning the UserName to a variable is superfluous as it could be easily achieved using the line MsgBox(UserName()), However you will probably need to check the condition of the username so something like the following code would probably be more useful.

Dim Person As String
Person = UserName()
If Person <>”neil_warwick” then
MsgBox (“You are an un-authorised user”)
End If