VBA Code to Get Logged in User Name

How to Write Excel VBA to Get User Name in an Excel File

Sometimes in VBA projects, a programmer is required to control the access on the data or sheets. This can be achieved using two ways:

1. Design a login userform and display it on the open event of the workbook. Based on the credentials, you can control the access on the data
2. Instead of using login userform, you can get the system login user id and control the access on the data

Excel Tricks

Get User Name Syntax Code


Expression A variable that represents an application object.


Sub Get_Username()

ActiveCell.Value = Application.UserName

End Sub

Here is sample code to write EXCEL VBA or macro to get user name

'This function gets the logged in user name and
'displays it on the sheet
Sub GetLoggedInUserName()
    'Declare variable
    Dim strUserName As String
    'Get system logged in user name
    strUserName = Environ("Username")
    'Display the user name on sheet1
    Sheet1.Range("B4").Value = strUserName
End Sub

To use this code in your Excel file, follow below steps:

1. Open an Excel file
2. Press Alt+F11
3. Insert a Module (Insert>Module) from menu bar
4. Paste the code in the module
5. Now add a shape in Excel sheet
6. Give a name to the shape like ‘Get Logged In User Name’
7. Right click on the shape and select ‘Assign Macro…’

Excel Tricks

8. Select ‘GetLoggedInUserName’ from the list and click on ‘Ok’ button

Excel Tricks

9. Done, click on the shape to get the logged in user name

Excel Tricks

Hope you liked this article!!

Here are some other VBA codes which you can use in Excel:

Subscribe our blog for new amazing excel tricks 

Please leave your comments in below section.

Excelsirji.com was started with the thought of making people experience easy while working with Excel, data analytics, vba, automations etc.

Leave a Reply

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