Получение полного имени пользователя Windows макросом VBA
Чтобы получить полное имя пользователя в Windows, можно использовать функцию UserFullName:
Sub ПримерИспользованияUserFullName() ПолноеИмяПользователяWindows = WMI_UserFullName MsgBox ПолноеИмяПользователяWindows End Sub
Данная функция использует интерфейс WMI для получения необходимых данных.
Function WMI_UserFullName() As String login$ = CreateObject("WScript.Network").UserName ' читаем логин текущего пользователя Set objWMIService = GetObject("winmgmts://./root/CIMV2") Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_UserAccount", , 48) For Each objItem In colItems ' перебираем все учётные записи If objItem.Name = login$ Then WMI_UserFullName = objItem.FullName Next End Function
Посмотреть список всех учётных записей пользователей на компьютере можно следующим кодом:
Sub WMI_username() Set objWMIService = GetObject("winmgmts://./root/CIMV2") Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_UserAccount", , 48) For Each objItem In colItems Debug.Print "FullName: " & objItem.FullName Next End Sub
Результат работы этого кода:
FullName: ASP.NET Machine Account
FullName: Учетная запись помощника для удаленного рабочего стола
FullName: CN=Microsoft Corporation,L=Redmond,S=Washington, C=US
FullName:
FullName: VBA Developer
Если же вам нужно получить только логин (имя пользователя) Windows, то код будет заметно проще:
(все 3 способа равнозначны — возвращают один и тот же результат)
Sub ПолучениеИмениПользователяWindows() ' первый способ (читаем из переменной окружения) username1 = Environ("USERNAME") Debug.Print "username 1: " & username1 ' второй способ (используем объект WScript.Network) username2 = CreateObject("WScript.Network").UserName Debug.Print "username 2: " & username2 ' третий способ (читаем значение из реестра Windows) key$ = "HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows NTCurrentVersionRegisteredOwner" username3 = CreateObject("WScript.Shell").RegRead(key$) ' читаем из реестра Debug.Print "username 3: " & username3 End Sub
PS: При создании этого макроса была использована программа WMI Code Creator:
- 47196 просмотров
Не получается применить макрос? Не удаётся изменить код под свои нужды?
Оформите заказ у нас на сайте, не забыв прикрепить примеры файлов, и описать, что и как должно работать.
I just need to get the name of the current user so I can access the app data folder within their folders….
I have to do this in VBA so yeah…help please.
Lance Roberts
22.2k32 gold badges112 silver badges129 bronze badges
asked Jun 6, 2011 at 17:07
0
I believe it’s something like
Environ("Username")
answered Jun 6, 2011 at 17:12
1
You do not need user name to know which folder is app data folder.
You need to use the SHGetFolderPath
function with the CSIDL_APPDATA
value.
Private Declare Function SHGetFolderPath Lib "shell32.dll" Alias "SHGetFolderPathA" (ByVal hwnd As Long, ByVal csidl As Long, ByVal hToken As Long, ByVal dwFlags As Long, ByVal pszPath As String) As Long
Private Const CSIDL_APPDATA As Long = &H1A
Private Const MAX_PATH As Long = 260
Dim s As String
s = String$(MAX_PATH, 0)
SHGetFolderPath 0, CSIDL_APPDATA, 0, 0, s
MsgBox Left$(s, InStr(1, s, vbNullChar))
answered Jun 6, 2011 at 17:15
GSergGSerg
75.3k17 gold badges160 silver badges340 bronze badges
1
Similar to accepted answer (Environ(«username»), there is an environment variable available for the App Data folder, so you can get it using:
Environ("APPDATA")
FYI, here is a good link for showing the full list of Environ Variables. There are a few that are windows universal, and some that can be registered as being application specific.
answered Jul 21, 2020 at 0:07
ainwoodainwood
9927 silver badges17 bronze badges
0
Excel VBA Macro to Get Username
Using Excel VBA, get username who is currently logged in & active, get author name who edited the Excel workbook, Ms Office Username, Network userid etc.,
Here are different kind of Username properties & corresponding command.
Before using them, read further in detail.
Purpose | VBA Command |
---|---|
1. MsOffice/Excel username | Application.username |
2. Windows Active Logged in Username | Environ(“Username”) |
3. Windows API | apiGetUserName |
4. Network Username | WScript.Network |
5. VBA Username from Windows Registry | CreateObject(“wscript.shell”). RegRead(“HKEY_CURRENT_USERSoftwareMicrosoft OfficeCommonUserInfoUserName”) |
6. Get the Author name or Username who edited an Excel workbook |
ThisWorkbook.BuiltinDocumentProperties(“Author”) |
Well that’s piece of cake if you know bit of VBA already. But, What if I say there are more ways!!!
Would You be interested in knowing them as well?
Lets find out.
Different Method to Find Windows UserName
Let’s see the easiest & most used one first.
- System Environment Variables – Windows login user
- Application.username – MS Office user name
- Windows API ‘apiGetUserName’ Function
- Network UserName
- Username from Windows Registry key
In some cases, if the easiest one did not work out, follow the next possible method.
1. Insert Windows Username in Excel Cell
There is no built in function to get username to a worksheet cell. This has to be done by defining a user defined function.
To do this, press Alt+ F11, go to VB editor, insert a new module & enter this code.
Function GetUserName() As String
GetUserName = Environ$("username")
'or
'GetUserName = Application.UserName
End Function
Then open the worksheet, then insert this formula “=GetUserName()” and press “Enter” key.
Now, the cell will execute the function and display the Windows logged in username in the cell.
2. VBA Application.Username – Excel User
Well this is the easiest of all the method and does not require any references to be added to any library or DLL.
You can manually change this user name from this menu option: File – Options – General as in this image.
Just copy-paste this code to Excel or Word VB Editor and run it.
Sub GetUserName_AppUser()
Dim strUserName As String
'Use the Application Object to get the Username
strUserName = Application.UserName
MsgBox "Current Logged In UserName is:" & strUserName
End Sub
This Excel macro code will display the current Windows username, who is also executing this Excel or Word App.
3. Excel VBA Get Username from System Environment Variables
Open Command prompt and type ‘Set’ and press Enter. This command will display list of all the Environment variables and values stored in it. In this list, we have an Environment variable “USERNAME” and it will have the active logged in username for that session.
We can write macro to read this Environment Variable and get the user id.
Sub GetUserName_Environ()
Dim idx As Integer
'To Directly the value of a Environment Variable with its Name
MsgBox VBA.Interaction.Environ$("UserName")
'To get all the List of Environment Variables
For idx = 1 To 255
strEnvironVal = VBA.Interaction.Environ$(idx)
ThisWorkbook.Sheets(1).Cells(idx, 1) = strEnvironVal
Next idx
End Sub
Note: This VBA macro can also be used to read all the Environment variables from system for that login session.
4. Using Windows API ‘apiGetUserName’ Function
Microsoft provides many other variants of this function. So, you can choose to use this function or any other available
APIs based on your need. To use this API, declare the function before calling the function.
'For 32-bit office installation
'Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
' "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
'For 64-bit office installation
Private Declare PtrSafe Function apiGetUserName Lib "advapi32.dll" _
Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As LongPtr) As Long
Sub Get_UserName_WINAPI()
'Declare Variables
Dim Returned_Val_Length As Variant
Dim API_Return_Status As Variant
Dim Returned_UserName As String
'Define Space for Variables
Returned_UserName = String$(254, 0)
Returned_Val_Length = 255
'Call the API and get the User Details
API_Return_Status = apiGetUserName(Returned_UserName, Returned_Val_Length)
'Remove unwanted details from Return value and get only Username
Returned_UserName = Mid(Trim(Returned_UserName), 1, Returned_Val_Length - 1)
End Sub
5. Network UserName in Excel VBA
The WScript Object is used here to get the Network Username for the current logged in user.
Create an instance for the object Wscript.Network and use it to fetch the User and Computer Details as explained below.
Sub GetUserName_Environ()
Dim ObjWshNw As Object
Set ObjWshNw = CreateObject("WScript.Network")
MsgBox ObjWshNw.UserName
MsgBox ObjWshNw.ComputerName
MsgBox ObjWshNw.UserDomain
End Sub
All these combination of codes, fetch current Windows user name details to Excel.
Also Read: How to Password Protect Office Excel, PPT and Word Document?
5.1. From Windows Registry
Windows system stores numerous detail in its registry. Details like Operating system features, parameters, installed software, users, etc.,
This code fetches the user info from registry within Excel.
Function getUsernameWindows() As String getUsernameWindows = CreateObject("wscript.shell").RegRead("HKEY_CURRENT_USERSoftwareMicrosoftOfficeCommonUserInfoUserName") End Function
We will be in need of these code tricks when, We share any Office document with other users and we need to collect the user details whoever is accessing it or restrict users from using this document based on their login id.
Read Also:
- Get list of Tasks running in System from Task Manager.
External References
- Windows API detail from Microsoft Support Website.
- Fetching detail from Environment Variable.
- Network User details from WScript.Network.
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
Method 1: Get Username in VBA Code
Sub GetLoggedInUserName()Dim strUserName As String
strUserName = Environ("Username")
Sheet1.Range("B4").Value = strUserName
End Sub
Method 2: Get UserName Syntax Code
expression.UserName
Expression A variable that represents an application object.
Example
Sub Get_Username()ActiveCell.Value = Application.UserName
End Sub
Method 3: Wscript.Network
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
Download Practice File
You can also practice this through our practice files. Click on the below link to download the practice file.
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
Recommended Articles
- Create Pareto chart in Excel
- Time and Motion study-complete guide
- Find duplicates in Excel
- VBA to Read Excel Data using a data connection string
- Few simple Excel tips-Excel learners should know
Excel VBA Course : Beginners to Advanced
We are currently offering our Excel VBA Course at discounted prices. This courses includes On Demand Videos, Practice Assignments, Q&A Support from our Experts. Also after successfully completion of the certification, will share the success with Certificate of Completion
This course is going to help you to excel your skills in Excel VBA with our real time case studies.
Lets get connected and start learning now. Click here to Enroll.
Secrets of Excel Data Visualization: Beginners to Advanced Course
Here is another best rated Excel Charts and Graph Course from excelsirji. This courses also includes On Demand Videos, Practice Assignments, Q&A Support from our Experts.
This Course will enable you to become Excel Data Visualization Expert as it consists many charts preparation method which you will not find over the internet.
So Enroll now to become expert in Excel Data Visualization. Click here to Enroll.
Automate Tasks using Excel VBA Utility Tools
-
Quickly Move or Delete Files or Folder >> Click here -
Handle Duplicate Files with Automated Utlity >> Click here -
Generate Dummy Data For Testing >> Click here -
Excel Files and Sheets Consolidator >> Click here -
Manage Outlook Emails efficiently >> CLick here -
Send Bulk Emails wiht our Excel Automation >> Click here
Here are some other free Excel VBA Tools which may help you to increase productivity in your day to day jobs. Click here
- Remove From My Forums
-
Question
-
We log onto our network with a three letter user name e.g. ADG. Can I return the user name of the person opening my Access Database with VBA?
I want to customise the options available to the user without using the security features built into Access.
Answers
-
This will provide you with the information you desire. I use it often in the default value of a field.
(Environ$(«Username»))
-
Many thanks Carbo,
Environ$(«Username») returned «adg» as expected. Thanks also Peter, but Application.CurrentUser returned «Admin», which was not the user I was seeking this time.
While searching on Microsoft.com I also found the below code which works, but I prefer the simple approach above.
‘ Declare for call to mpr.dll.
Declare Function WNetGetUser Lib «mpr.dll» _
Alias «WNetGetUserA» (ByVal lpName As String, _
ByVal lpUserName As String, lpnLength As Long) As LongConst NoError = 0 ‘The Function call was successful
Sub GetUserName()
‘ Buffer size for the return string.
Const lpnLength As Integer = 255‘ Get return buffer space.
Dim status As Integer‘ For getting user information.
Dim lpName, lpUserName As String‘ Assign the buffer size constant to lpUserName.
lpUserName = Space$(lpnLength + 1)‘ Get the log-on name of the person using product.
status = WNetGetUser(lpName, lpUserName, lpnLength)‘ See whether error occurred.
If status = NoError Then
‘ This line removes the null character. Strings in C are null-
‘ terminated. Strings in Visual Basic are not null-terminated.
‘ The null character must be removed from the C strings to be used
‘ cleanly in Visual Basic.
lpUserName = Left$(lpUserName, InStr(lpUserName, Chr(0)) — 1)
Else‘ An error occurred.
MsgBox «Unable to get the name.»
End
End If‘ Display the name of the person logged on to the machine.
MsgBox «The person logged on this machine is: » & lpUserNameEnd Sub