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
Sub GetLoggedInUserName()
Dim strUserName As String
strUserName = Environ("Username")
Sheet1.Range("B4").Value = strUserName
End Sub
expression.UserName
Expression A variable that represents an application object.
Example
Sub Get_Username()
ActiveCell.Value = Application.UserName
End Sub
Function CurrentUser()
Dim objNetwork As Object
Dim strUserName As String
Set objNetwork = CreateObject("Wscript.Network")
strUserName = objNetwork.UserName
MsgBox strUserName
End Function
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:
Here are some other free Excel VBA Tools which may help you to increase productivity in your day to day jobs. Click here
If you have data on paper that you want to add to Excel, you can take a photo of it, save the photo to your computer, and upload the data into Excel. This saves time…
Merge Excel Files From last few months, we have been receiving frequent requests from users for a VBA tool which can consolidate Excel files from a folder. So here we come with one more free…
VBA Code to Find Last used Column or Row in Excel Sometimes as a developer, you need to take actions in Excel sheets based on last row or column. In Excel, there are two kinds…
Lock Cells to avoid editing, Hide Formulas Sometimes you create amazing projects, dashboards however people can make mistakes and edit the calculations, formats what you have made. Still you can protect the sheets, workbooks and…
VBA Code to send Outlook Emails Sending bulk emails is a very common activity, there are many office activities that need a person to send bulk emails to single or multiple recipients. You also may…
How to Insert Symbol in Excel? I came across many queries regarding inserting special symbols in Excel. Here we are guiding how you may do this quickly in excel. Follow these steps and you may…
Does not work with Azure joined computers. Environ(“username”) appears to return blank
Hi,
Can you give an try to below code: