Получение полного имени пользователя 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:
- 47199 просмотров
Не получается применить макрос? Не удаётся изменить код под свои нужды?
Оформите заказ у нас на сайте, не забыв прикрепить примеры файлов, и описать, что и как должно работать.
Получить имя учетной записи Microsoft office |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
Excel VBA Login Form
It is possible to create a login-based user form in Excel VBA with all the login ID drop-down lists, and it will share the password separately. However, at some point, you must have an idea of creating a password-based login user form, which requires the user to pick their user ID and enter the password to access the required worksheet.
Table of contents
- Excel VBA Login Form
- How to Create a Login User Form?
- Step 1: Insert User Form
- Step 2: Design Userform
- Step 3: Code
- Things to Remember
- Recommended Articles
- How to Create a Login User Form?
This article will show you how to create a login UserForm using Excel VBA.
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Login Form (wallstreetmojo.com)
How to Create a Login User Form?
For example, assume you have region-wise sales numbers in different worksheets. We have four different zone names, and each zone worksheet has its related data only. Now, the idea is to create a login form where the “East” zone sales head should see only “East” zone data. Not any other zones, but as an admin, you should see all the zones’ worksheets.
You can download this VBA Login Excel Template here – VBA Login Excel Template
First, we need to insert a sheet name called “Admin.” Then, in this admin sheet, we need to create “Login ID” and “Password” credentials.
We have named the zone and password the same. You can change this later. We have created the name rangeName range in Excel is a name given to a range for the future reference. To name a range, first select the range of data and then insert a table to the range, then put a name to the range from the name box on the left-hand side of the window.read more for zone names as “ZoneList.” This “Name Manager” will be used later on this login UserForm.
When the user opens the file, they should see one dummy sheet in the background, so create a new sheet and name it the “Dummy” sheet.
Using these worksheets, we will create a login UserForm.
Step 1: Insert User Form
Press ALT + F11 key to open the VBA EditorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more window.
- From the “Insert” tab, insert “UserForm.”
- It will create a new UserForm like the below one.
- Press the F4 key to see the “Properties” window. From this window, change the name of the UserForm to “LogInUF.”
- Similarly, using this properties window, we can play with the properties of the UserForm. We have made some of the property changes. We can refer to the below properties window to apply changes to the properties of the UserForm.
- Now, my UserForm looks like this.
Step 2: Design Userform
- From the toolbox of the UserForm, insert two label boxes and enter the text, as shown below.
- From the toolbox, insert “Combo Box.”
- For this ComboBox excelCombo Box in Excel is a type of data validation tool that can create a dropdown list for the user to select from the pre-determined list. It is a form control which is available in the insert tab of the developer’s tab.read more, we need to get the zone names from the worksheet “Admin Sheet,” so from the properties window of the “Combo Box,” first give a name to this combo box as “Zone_List_ComboBox” under the “Name” property.
- From the “RowSource” property of the combo box, enter the name given to the zone list in the “Admin Sheet.”
- Now, our ComboBox should show zone names in its dropdown list in excelA drop-down list in excel is a pre-defined list of inputs that allows users to select an option.read more.
- For “Enter Your Password,” we need to insert a “Text Box” from the toolbox.
- For this “Text Box,” we need to change the “Name” property and change it as “Password_TB.”
Now in the coding for the VBAVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more login form, “Combo Box” will be referred to by the name “Zone_List_ComboBox,” and “Text Box” will be referred to by the name “Password_TB.”
- Insert two “CommandButton” and enter the text as “Log In” and “Log Out.”
For the “Log In” command button, change the name property to “Login_CommandButton,” and for the “Log Out” command button, change the name property to “LogOut_CommandButton.”
Step 3: Code
We completed the VBA login UserForm design part. Next, it is time to write the code to create a login-based UserForm in Excel VBA.
- Double click on the “Log In” Command Button. It will open a blank sub procedure like the below one.
Inside this procedure, we need to write the code about what should happen if we press the “Log In” button.
We have already written the code. We can copy and paste the code from below inside the above procedure.
Code:
Private Sub Login_CommandButton_Click() If Zone_List_ComboBox.Value = "" Then MsgBox "Zone Cannot be Blank!!!", vbInformation, "Zone Name" Exit Sub End If If Password_TB.Value = "" Then MsgBox "Password Cannot be Blank!!!", vbInformation, "Password" Exit Sub End If If Zone_List_ComboBox.Value = "Admin" And Password_TB.Value = "Admin" Then Unload Me Dim Ws As Worksheet For Each Ws In ActiveWorkbook.Worksheets Ws.Visible = xlSheetVisible Next Ws Sheets("Admin").Select Else Dim ZoneName As String Dim Password As Variant ZoneName = Zone_List_ComboBox.Value Password = Application.WorksheetFunction.VLookup(ZoneName, Sheets("Admin").Range("A:B"), 2, 0) If Password <> Password_TB.Value Then MsgBox "Password is not matching", vbInformation, "Wrong Password" Exit Sub End If If Password = Password_TB.Value Then Unload Me Sheets(ZoneName).Visible = True Sheets(ZoneName).Select ActiveSheet.Range("A1").Select End If End If End Sub
Similarly, double click on the “Log Out” command button and enter the below code.
Code:
Private Sub LogOut_CommandButton_Click() ThisWorkbook.Save ThisWorkbook.Close End Sub
Now, double click on “UserForm” (not on any of the buttons inserted) and add the below code.
Code:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) ' Prevents use of the Close button If CloseMode = vbFormControlMenu Then MsgBox "Clicking the Close button does not work." Cancel = True End If End Sub
- Now, double-click on the “ThisWorkbookVBA ThisWorkbook refers to the workbook on which the users currently write the code to execute all of the tasks in the current workbook. In this, it doesn’t matter which workbook is active and only requires the reference to the workbook, where the users write the code.read more” icon. It will open up below the blank code field.
Now add the below code in this blank field.
Code:
Private Sub Workbook_Open() Dim Ws As Worksheet Application.DisplayAlerts = False Application.ScreenUpdating = False For Each Ws In ActiveWorkbook.Worksheets If Ws.Name <> "Dummy" Then Ws.Visible = xlSheetVeryHidden End If Next Ws LogInUF.Show End Sub
- We have completed the coding part of the form. Next, save the workbook as a “Macro-Enabled” workbook and reopen the workbook. Upon reopening the workbook, we should see the below window.
- We must choose the respective zone name from this UserForm and enter the associated password. For example, we will choose the “East” zone from the dropdown and enter the password.
- If we click “Log In,” we can see only the “East” zone worksheet.
Similarly, if we log in with “Admin,” we can access all the worksheets.
Like this, we can create login-based password-protected worksheet access.
Things to Remember
- It would help if we used the same names given to the UserForm, text box, command button, and combo box in the coding.
- We can change the zone name and password according to your wish.
Recommended Articles
This article has been a guide to VBA Login. Here, we discuss how to create a login form in Excel VBA with the help of an example and a downloadable Excel sheet. You can learn more about VBA from the following articles: –
- VBA Object Required
- ENVIRON Function in VBA
- VBA Close UserForm
- Excel Forms for Data Entry
Excel VBA Login Form
VBA Login is a unique way to protect excel workbook and worksheets. Although we have options of Protect Sheet and protect workbook which is available in Review menu option, which we have the fix patterns of locking the worksheet and workbook. With the help of the VBA login, we have created a customize login box by which we can create dialog box or login form in which we can authorize the login id and password to access the complete excel workbook and any specific worksheets. For better understanding, suppose we have an Excel file that has multiple sheets and each sheet has some confidential data to be protected. And each data is meant for everyone, so we can create a login form by giving every user their login id and password and user will only be able to open and access the data which is meant for him. This could be done only by VBA Login.
How to Generate Login User Form in VBA?
We will learn how to generate logic user form in Excel by using the VBA Code.
You can download this VBA Login Excel Template here – VBA Login Excel Template
Example #1
In this example, we will learn how to create login box using User form. For this, follow the below steps:
Step 1: For this open VBA and from the Insert menu tab select UserForm.
Step 2: Now once we get the UserForm opened, from the toolbox select the Label option and create a label box in Userform.
Step 3: At the left hand side we have a Properties of the Label which we have created. We can change the name, font, size, and color of created label.
Step 4: As you can see in below screenshot, we have change the name user form as Label1, Font as Arial Narrow, Fore Color as Blue and Caption as Enter User Name. We can further customize it.
Step 5: Now we will create a text box here to enter the user name for login as shown below.
Step 6: Now we would insert a label for entering the password.
Step 7: Again we would change the name of Label, color, font, size, and name as required below.
Step 8: Insert a text box for entering the password against the Password label.
Step 9: And last, create a login button with the help of the Command button to click on it.
Step 10: Now edit the properties of created Command Button from the Properties window at left.
Step 11: We are done with part of creating a login form in VBA. Now we will write a small VBA code to make this login work. For this, double click anywhere on created UserForm and in that write the sub-procedure as shown below.
Code:
Private Sub Login_Click() End Sub
Step 12: Open an IF – End IF loop and write the condition as if the Login flag is FALSE then activate the worksheet and then show login.
Code:
Private Sub Login_Click() If LoginFlag = False Then Worksheets("Sheet1").Activate LogIn.Show End If End Sub
Step 13: Now we will compile the code by pressing the F8 key and And run the code by pressing the Play button located below the menu bar, we would get the Login box.
Example #2
Although there are various ways to create a VBA Login. But we will be seeing another code where we will be using IF – End IF loop to list the login. For this, again follow the same process to create a UserForm which we have seen in example-1. Include 2 labels and 2 text boxes, each for entering User Name and Password.
Step 1: We can use the same User Form which we have seen in example-1 as there is no change in the pattern of login box or create a new one. Now double click on User form and write the sub procedure. Now in the open the IF – End IF loop for the condition, if Username box is blank then give me the message as “Enter Login Credentials”, else message “Enter Username”.
Code:
Private Sub Login_Click() If UsernameBox.Value = "" Then If PasswordBox.Value = "" Then MsgBox "Enter Login Credentials!" Else MsgBox "Enter Username" End If End Sub
Step 2: Now define the Else If condition again, if username value is USER1 and password is Blank then give me the message as “Enter Password” and if the password is “abcd” then hide the application or else give the message as “Re-Enter Login Credentials.”
Code:
Private Sub Login_Click() If UsernameBox.Value = "" Then If PasswordBox.Value = "" Then MsgBox "Enter Login Credentials!" Else MsgBox "Enter Username" End If ElseIf UsernameBox.Value = "USER1" Then If PasswordBox.Value = "" Then MsgBox "Enter Password" ElseIf PasswordBox.Value = "abcd" Then Me.Hide: Application.Visible = True Else MsgBox "Please Re-Enter Login Credentials." End If End Sub
Step 3: At last list the final IF condition for if the login password is incorrect or blank, then return the message “Enter Correct Credentials”.
Code:
Private Sub Login_Click() If UsernameBox.Value = "" Then If PasswordBox.Value = "" Then MsgBox "Enter Login Credentials!" Else MsgBox "Enter Username" End If ElseIf UsernameBox.Value = "USER1" Then If PasswordBox.Value = "" Then MsgBox "Enter Password" ElseIf PasswordBox.Value = "abcd" Then Me.Hide: Application.Visible = True Else MsgBox "Please Re-Enter Login Credentials." End If Else If PasswordBox.Value = "" Then MsgBox "Enter Password" Else MsgBox "Please Enter Correct Credentials." End If End If End Sub
Step 4: Open a new sub procedure for Command Button which we created for Login, and write the below line for quitting the application.
Code:
Private Sub CommandButton2_Click() ThisWorkbook.Application.Quit End Sub
Step 5: And at last, write the final sub procedure for Created UserForm name to close the application.
Code:
Private Sub LoginArena_QueryClose(Cancel As Integer, CloseMode As Integer) ThisWorkbook.Application.Quit End Sub
Step 6: Final would look like this below.
Step 7: Now compile the each and every step of the code and run it then. In the popped up login form, Enter the user name as USER1 and the password as “abcd” in designated section as per code. If we press ENTER or click on LOGIN, then the code will be exited and we will be returned to the VBA window.
Pros & Cons of VBA Login
- VBA Login allows different users to login in a different way in a single Excel worksheet.
- We restrict the user to the data which is meant for him/ her.
- With the help of VBA Login, we can customize the excel workbook and give the different login user id and password to different users to access the data.
- Because of lengthy lines of code, the process of creating VBA Login is quite complicated.
Things to Remember
- We can use Protect Worksheet and Protect Workbook which also consider the password for login and accessing the data. But the password would be the same for each login. Whereas VBA Login allows use to create multiple user id and password.
- Always create a simple user form first, because when we customize the data the size and attributes of created shapes and boxes, we may end of complicating the coding part.
- We can create VBA login to direct the user to his login area after login.
- Once coding is done, save the Excel in macro-enabled excel format.
Recommended Articles
This is a guide to the VBA Login. Here we discuss how to Generate Login User Form in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Name Worksheet
- VBA Input
- VBA Solver
- VBA Selecting Range
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.