VBA Code to Get Logged in User Name

VBA Code to Get Logged in User Name

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 access the control 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

'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

Author:
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 *

Are you a Data Enthusiast?

Join us for a ride on your data and automate your stuffs

Business Analytics
Data Analyst
Programming for Data Science
Predictive Analytics for Business