Получение полного имени пользователя 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_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\RegisteredOwner" username3 = CreateObject("WScript.Shell").RegRead(key$) ' читаем из реестра Debug.Print "username 3: " & username3 End Sub
PS: При создании этого макроса была использована программа WMI Code Creator:
- 50606 просмотров
Excel VBA Macro to Get Username
Using Excel VBA, get username who is currently logged into Windows PC or get author name who edited the Excel workbook, Ms Office Username, Network userid etc.,
Refer the below table to understand what kind of username you can fetch and its corresponding command.
Before using them, read further in detail in below sections, so that you use the correct variant.
Purpose | VBA Command |
---|---|
1. Get 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_USER\Software\Microsoft\ Office\Common\UserInfo\UserName”) |
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 them one by one in the order of how frequent they are used.
- 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
If you would like to get username of Windows login to a worksheet cell, remember there is no Excel formula or built-in function to do this.
Good news is that you can use the below code. this can act as a user defined function or custom Excel formula.
To do this, press Alt+ F11 from your Excel file,then go to VB editor, insert a new module & paste this code.
Function GetUserName() As String
GetUserName = Environ$("username")
'or
'GetUserName = Application.UserName
End Function
Then open the worksheet, 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.
To get this Username in a VBA code, we have built-in function. Use the below code in your 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.
The above two are the most used methods.
In case you are interested more in this area, then refer the other methods.
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 that get username within Excel VBA.
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. Get 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?
6. Username From Windows Registry
Windows system stores numerous detail in its registry. Details like Operating system features, parameters, installed software, users list & details, etc.,
With this Excel vba get username and user details from registry of a windows OS to the Excel worksheet.
Function getUsernameWindows() As String getUsernameWindows = CreateObject("wscript.shell").RegRead("HKEY_CURRENT_USER\Software\Microsoft\Office\Common\UserInfo\UserName") 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/Applications/Programs 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.
Many times, we are required to fetch User Names in Excel. Unfortunately, getting User Names in Excel is possible only through VBA. These are very small pieces of VBA codes and even a person not knowing VBA can make use of them by following the instructions here.
I am going to discuss the various type of User Names which we may be required to extract.
First, for beginners in VBA, you need to follow below instructions to make these work.
1. Make a backup of your workbook just to be on safer side.
2. Open your workbook and ALT+F11
3. Locate your Workbook name in Project Explorer Window
4. Right click on your workbook name > Insert > Module
5. Copy paste the Macro code given
6. Go back to your Workbook and ALT+F8 to display Macro Window
7. Save your file as .xlsm if you intend to reuse Macro.
8. If your function name is MyFunction, in a cell just put =MyFunction() to get the output. Hence, for the Function, GetWindowsUser, just put =GetWindowsUser() to get the name of the user who is logged into Windows.
1. Get the Name of the User who is Logged into Windows
You use the combination of User Name and Password to log into your windows. This Function retrieves that User Name which is used by you to log into your windows. The same user name password combination you use when the screen saver lock is put or you lock your computer by CTRL+ALT+DEL.
To get Windows User Name, use GetWindowsUser function. To get this User Name, put following in a cell
=GetWindowsUser()
Function GetWindowsUser() As String Application.Volatile GetWindowsUser = Environ$("UserName") End Function
2. Get the Name of User Name of the Application
Excel may have a user name which is called Application User Name and it may be different than the user who is logged into the Windows. This is found under File > Options > General. This particular application name is very important as this is what gets logged by Excel under Created By and Last Saved by users.
To get Application User Name, use GetExcelUser function. To get this user name, put following in a cell –
=GetExcelUser()
Function GetExcelUser() As String Application.Volatile GetExcelUser = Application.UserName End Function
3. Get the User Name of the Current User of Outlook
Since Outlook is an integrated part of MS Office, hence sometimes, you may need to retrieve the User Name of the Current User of Outlook.
To get Outlook Current User Name, use GetOutlookCurrentUserName function. To get this user name, put following in a cell –
=GetOutlookCurrentUserName()
Function GetOutlookCurrentUserName() As String Dim NameSpace As Object Application.Volatile Set NameSpace = CreateObject("Outlook.Application").GetNameSpace("MAPI") GetOutlookCurrentUserName = NameSpace.CurrentUser End Function
4. Get the E Mail ID of Current User of Outlook
Another information, you may need may be E Mail ID of Current User of Outlook.
To get Outlook Current User E Mail ID, use GetOutlookCurrentUserEMail function. To get this user name, put following in a cell –
=GetOutlookCurrentUserEMail()
Function GetOutlookCurrentUserEMail() As String Dim NameSpace As Object Application.Volatile Set NameSpace = CreateObject("Outlook.Application").GetNameSpace("MAPI") GetOutlookCurrentUserEMail = NameSpace.Accounts.Item(1) End Function
5. Get the Active Directory User ID
In case, you need to retrieve Active Directory User ID, use GetADUserDN function. To get this user name, put following in a cell –
=GetADUserDN()
Function GetADUserDN() As String Application.Volatile GetADUserDN = CreateObject("ADSystemInfo").UserName End Function
6. Get Active Directory Full Name of the User
In case, you need to get Full Name of the User from Active Directory, use GetADFullUserName function. To get this user name, put following in a cell –
=GetADFullUserName()
' Source - http://www.mrexcel.com/forum/excel-questions/2252-get-windows-user-name-2.html Function GetADFullUserName() As String Dim objUser Dim strName Dim arrLDAP Dim intIdx Dm strLDAP Application.Volatile On Error Resume Next strLDAP = CreateObject("ADSystemInfo").UserName strName = "" Set objUser = GetObject("LDAP://" & strLDAP) If Err.Number = 0 Then strName = objUser.Get("givenName") & Chr(32) & objUser.Get("sn") End If If Err.Number <> 0 Then arrLDAP = Split(strLDAP, ",") For intIdx = 0 To UBound(arrLDAP) If UCase(Left(arrLDAP(intIdx), 3)) = "CN=" Then strName = Trim(Mid(arrLDAP(intIdx), 4)) End If Next End If Set objUser = Nothing GetADFullUserName = strName End Function
7. User Who Created the Excel Document
To get the information about the Excel User (This is the same type User Name which you retrieved in point 2 i.e. Application User Name) who created this particular Excel Document, you can use GetCreatedByUser() function. Just put following in a cell –
=GetCreatedByUser()
This particular information can be derived manually by right clicking an Excel document > Properties > Details tab
Function GetCreatedByUser() As String Application.Volatile GetCreatedByUser = ThisWorkbook.BuiltinDocumentProperties(3) End Function
8. User Who Last Modified (Updated) the Excel Document
To get the information about the Last Excel User (This is the same type User Name which you retrieved in point 2 i.e. Application User Name) who modified this particular Excel Document, you can use GetLastModifierUser() function. Just put following in a cell –
=GetLastModifiedByUser()
This particular information can be derived manually by right clicking an Excel document > Properties > Details tab
Function GetLastModifiedByUser() As String Application.Volatile GetLastModifiedByUser = ThisWorkbook.BuiltinDocumentProperties(7) End Function
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
In the first method, we can make use of Excel VBA inbuild function named Environ to get the user name of the current logged-in user. This is the most common code used by the developers.
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("C4").Value = strUserName
End Sub
Method 2: Get UserName Syntax Code
Second method is to use Application.UserName property. Note that it may not work sometime as it tries to get user details from the installed Excel application.
Sub Get_Username()
Sheet1.Range("C5").Value = Application.UserName
End Sub
Method 3: Wscript.Network
Now a day few developers started reporting that both method 1 and 2 goes not work for few users. Here we can make use of below code which uses network object to get user details.
Function CurrentUser()
Dim objNetwork As Object
Dim strUserName As String
Set objNetwork = CreateObject("Wscript.Network")
strUserName = objNetwork.UserName
Sheet1.Range("C6").Value = 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
Automate Tasks using Excel VBA Utility Tools
Here are some other free Excel VBA Tools which may help you to increase productivity in your day to day jobs. Click here
Автор: Сан Последнее изменение: 2024 июля 10 г.
При работе с Excel иногда может потребоваться вставить имя пользователя Windows в ячейки. Вы можете вводить имя пользователя по одному вручную, но у меня есть несколько более эффективных способов сэкономить ваше время.
Вставить имя пользователя в ячейку с помощью VBA
Вставьте имя пользователя или другую информацию о книге в ячейку с помощью Kutools for Excel
Вставить имя пользователя в ячейку с помощью VBA
Здесь я представляю вам код VBA для быстрой вставки имени пользователя Windows в диапазон ячеек Excel.
1. Нажмите Alt + F11 ключи для включения Microsoft Visual Basic для приложений окна, нажмите Вставить > Модули, затем скопируйте и вставьте ниже код VBA в окно модуля.
VBA: введите имя пользователя.
Sub Usernameincell()
Range("A1:D5").Value = Application.UserName
End Sub
2. Нажмите Run или F5 ключ для запуска кода, затем имя пользователя вставляется в каждую ячейку в диапазоне A1: D5. Смотрите скриншот:
Вы можете изменить диапазон A1: D5 в коде VBA в соответствии с вашими потребностями.
Но если в указанном диапазоне есть какое-то содержимое, этот код VBA заменит содержимое ячейки только именем пользователя.
В этом случае вы можете использовать Kutools for Excel.
Вставьте имя пользователя или другую информацию в ячейку с помощью Kutools for Excel
Если вы хотите вставить имя пользователя Windows или другую информацию о книгах, такую как имя книги, имя рабочего листа, путь и имя книги в ячейку, нижний колонтитул или верхний колонтитул, вы можете использовать Kutools for ExcelАвтора Вставить информацию о книге.
Kutools for Excel, оснащен ИИ 🤖, предлагает более 300 удобных функций для упрощения ваших задач.
После бесплатная установка Kutools for Excel, сделайте следующее:
Нажмите Кутулс Плюс > Workbook > Вставить информацию о книге. Смотрите скриншот:
A: Выберите информацию, которую вы хотите вставить.
B: Выберите место для размещения вставленной информации.
C: Чтобы вставить верхний или нижний колонтитул, вы можете разместить
информация в Certer верхнего / нижнего колонтитула, слева от верхнего / нижнего колонтитула
нижний колонтитул или справа от верхнего / нижнего колонтитула.
Вставить путь и имя книги в ячейку
Вставить имя пользователя в центральный заголовок
Вставить текущую дату и время в правый нижний колонтитул
Нажмите здесь, чтобы узнать больше о Kutools for Excel, чтобы вставить информацию о книге.
Демонстрация: Вставка информации из рабочей книги с помощью Kutools
Kutools for Excel: Более 300 удобных инструментов у вас под рукой! Наслаждайтесь постоянно бесплатными функциями ИИ! Скачать
Лучшие инструменты для офисной работы
🤖 | Kutools AI Помощник: Революционный анализ данных на основе: Интеллектуальное исполнение | Генерировать код | Создание пользовательских формул | Анализ данных и создание диаграмм | Вызов функций Kutools… |
Популярные опции: Найдите, выделите или определите дубликаты | Удалить пустые строки | Объедините столбцы или ячейки без потери данных | Раунд без формулы … | |
Супер поиск: Множественный критерий VLookup | VLookup с несколькими значениями | VLookup по нескольким листам | Нечеткий поиск …. | |
Расширенный раскрывающийся список: Быстрое создание раскрывающегося списка | Зависимый раскрывающийся список | Выпадающий список с множественным выбором …. | |
Менеджер столбцов: Добавить определенное количество столбцов | Переместить столбцы | Переключить статус видимости скрытых столбцов | Сравнить диапазоны и столбцы … | |
Рекомендуемые функции: Сетка Фокус | Просмотр дизайна | Большой Формулный Бар | Менеджер книг и листов | Библиотека ресурсов (Авто текст) | Выбор даты | Комбинировать листы | Шифровать/дешифровать ячейки | Отправлять электронные письма по списку | Суперфильтр | Специальный фильтр (фильтровать жирным шрифтом/курсивом/зачеркиванием…) … | |
15 лучших наборов инструментов: 12 Текст Инструменты (Добавить текст, Удалить символы, …) | 50+ График Тип (Диаграмма Ганта, …) | 40+ Практических Формулы (Рассчитать возраст по дню рождения, …) | 19 Вносимые Инструменты (Вставить QR-код, Вставить изображение из пути, …) | 12 Конверсия Инструменты (Числа в слова, Конверсия валюты, …) | 7 Слияние и разделение Инструменты (Расширенные ряды комбинирования, Разделить клетки, …) | … и более |
Используйте Kutools на предпочитаемом вами языке — поддерживаются английский, испанский, немецкий, французский, китайский и более 40 других языков!
Улучшите свои навыки работы с Excel с помощью Kutools for Excel и почувствуйте эффективность, как никогда раньше. Kutools for Excel предлагает более 300 расширенных функций для повышения производительности и экономии времени. Нажмите здесь, чтобы получить функцию, которая вам нужна больше всего…
Вкладка Office: интерфейс с вкладками в Office и упрощение работы
- Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
- Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
- Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!