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

Get User Name Syntax Code
expression.UserName
Expression A variable that represents an application object.
Example
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…’

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

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

Hope you liked this article!!
Here are some other VBA codes which you can use in Excel:
- VBA Code to Check If Folder Exist
- VBA Code to Remove Duplicate Records
- VBA Code to hide Menu Ribbon in MS AccessÂ
- VBA Code to Sum Cells by colorÂ
- VBA Code to Convert Excel Range into HTML TableÂ
Subscribe our blog for new amazing excel tricksÂ
Please leave your comments in below section.
Does not work with Azure joined computers. Environ(“username”) appears to return blank
Hi,
Can you give an try to below code: