Vba excel учетная запись

Получение полного имени пользователя 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

EvgenyD

Дата: Вторник, 01.09.2015, 15:10 |
Сообщение № 1

Группа: Пользователи

Ранг: Участник

Сообщений: 74


Репутация:

19

±

Замечаний:
0% ±


Excel 2013

Добрый день, уважаемые форумчане!
Никак не могу найти каким образом получить имя учетной записи Microsoft.
Именно той, которая указана в меню Файл->Учетная запись (блок «Сведения о пользователе»)?

 

Ответить

Rioran

Дата: Вторник, 01.09.2015, 15:29 |
Сообщение № 2

Группа: Авторы

Ранг: Ветеран

Сообщений: 903


Репутация:

290

±

Замечаний:
0% ±


Excel 2013

EvgenyD, привет.

Оказалось неочевидно:

[vba]

[/vba]


Роман, Москва, voronov_rv@mail.ru
Яндекс-Деньги: 41001312674279

 

Ответить

_Boroda_

Дата: Вторник, 01.09.2015, 15:36 |
Сообщение № 3

Группа: Модераторы

Ранг: Местный житель

Сообщений: 16618


Репутация:

6465

±

Замечаний:
0% ±


2003; 2007; 2010; 2013 RUS

Дает имя пользователя.

А учетку можно так
[vba]

Код

Set SI_ = CreateObject(«ADSystemInfo»)
Set Un_ = GetObject(«LDAP://» & SI_.UserName)
UZ_ = Un_.DisplayName

[/vba]
Это не мое, давно уже где-то нашел


Скажи мне, кудесник, любимец ба’гов…
Платная помощь:
Boroda_Excel@mail.ru
Яндекс-деньги: 41001632713405 | Webmoney: R289877159277; Z102172301748; E177867141995

 

Ответить

EvgenyD

Дата: Вторник, 01.09.2015, 15:43 |
Сообщение № 4

Группа: Пользователи

Ранг: Участник

Сообщений: 74


Репутация:

19

±

Замечаний:
0% ±


Excel 2013

Rioran, это не выдает желаемого результата. Тут возможно есть еще важные моменты, которые надо было написать. Пользователи на Office 365 Buisness, соответственно у каждого свой логин microsoft — его то и нужно будет получить.
[vba][/vba] — выводит имя пользователя ПК
А мне нужно получить то, что на принтскрине в приложенном файле.

К сообщению приложен файл:

0769789.jpg
(26.6 Kb)

 

Ответить

Rioran

Дата: Вторник, 01.09.2015, 15:57 |
Сообщение № 5

Группа: Авторы

Ранг: Ветеран

Сообщений: 903


Репутация:

290

±

Замечаний:
0% ±


Excel 2013

_Boroda_, EvgenyD, странно, потому что у меня выводит именно то, что отмечено на рисунке. Microsoft Office профессиональный плюс 2013.


Роман, Москва, voronov_rv@mail.ru
Яндекс-Деньги: 41001312674279

 

Ответить

_Boroda_

Дата: Вторник, 01.09.2015, 16:06 |
Сообщение № 6

Группа: Модераторы

Ранг: Местный житель

Сообщений: 16618


Репутация:

6465

±

Замечаний:
0% ±


2003; 2007; 2010; 2013 RUS

Роман, а они у тебя не совпадают ли? Посмотри, что у тебя написано в Файл — Параметры — Имя пользователя?


Скажи мне, кудесник, любимец ба’гов…
Платная помощь:
Boroda_Excel@mail.ru
Яндекс-деньги: 41001632713405 | Webmoney: R289877159277; Z102172301748; E177867141995

 

Ответить

EvgenyD

Дата: Вторник, 01.09.2015, 16:06 |
Сообщение № 7

Группа: Пользователи

Ранг: Участник

Сообщений: 74


Репутация:

19

±

Замечаний:
0% ±


Excel 2013

Rioran, возможно из-за office 365 такая разница. Нашел в реестре, попробую использовать.

 

Ответить

Rioran

Дата: Вторник, 01.09.2015, 16:13 |
Сообщение № 8

Группа: Авторы

Ранг: Ветеран

Сообщений: 903


Репутация:

290

±

Замечаний:
0% ±


Excel 2013

_Boroda_, спасибо, ты прав, совпадают. Значит, у каждого приложения офиса есть возможность настроить отдельное имя пользователя.


Роман, Москва, voronov_rv@mail.ru
Яндекс-Деньги: 41001312674279

 

Ответить

EvgenyD

Дата: Вторник, 01.09.2015, 16:16 |
Сообщение № 9

Группа: Пользователи

Ранг: Участник

Сообщений: 74


Репутация:

19

±

Замечаний:
0% ±


Excel 2013

_Boroda_, Ваш вариант на второй строке ошибается automation Error. Я в этом ничего не смыслю, но кажется ADSystemInfo будет работать только при наличии настроенной Active Directory.

 

Ответить

_Boroda_

Дата: Вторник, 01.09.2015, 16:17 |
Сообщение № 10

Группа: Модераторы

Ранг: Местный житель

Сообщений: 16618


Репутация:

6465

±

Замечаний:
0% ±


2003; 2007; 2010; 2013 RUS

у каждого приложения офиса есть возможность настроить отдельное имя пользователя.

Не-а. Они взаимосвязаны. Измени в Ворде и оно изменится в Excele.


Скажи мне, кудесник, любимец ба’гов…
Платная помощь:
Boroda_Excel@mail.ru
Яндекс-деньги: 41001632713405 | Webmoney: R289877159277; Z102172301748; E177867141995

 

Ответить

EvgenyD

Дата: Вторник, 01.09.2015, 16:20 |
Сообщение № 11

Группа: Пользователи

Ранг: Участник

Сообщений: 74


Репутация:

19

±

Замечаний:
0% ±


Excel 2013

У меня эти сведения нашлись в ветке реестра:
HKEY_USERSS-1-5-21-1838117663-2728108920-1439421766-1000SoftwareMicrosoftOffice15.0CommonIdentityIdentitiesdc7cdd78f0fa498e_OrgId

 

Ответить

_Boroda_

Дата: Вторник, 01.09.2015, 16:26 |
Сообщение № 12

Группа: Модераторы

Ранг: Местный житель

Сообщений: 16618


Репутация:

6465

±

Замечаний:
0% ±


2003; 2007; 2010; 2013 RUS


Скажи мне, кудесник, любимец ба’гов…
Платная помощь:
Boroda_Excel@mail.ru
Яндекс-деньги: 41001632713405 | Webmoney: R289877159277; Z102172301748; E177867141995

 

Ответить

nilem

Дата: Вторник, 01.09.2015, 20:09 |
Сообщение № 13

Группа: Авторы

Ранг: Старожил

Сообщений: 1612


Репутация:

563

±

Замечаний:
0% ±


Excel 2013, 2016

не уверен, но вот это не подойдет?:
[vba]

Код

MsgBox Environ(«UserName»)

[/vba]


Яндекс.Деньги 4100159601573

 

Ответить

Manyasha

Дата: Вторник, 01.09.2015, 21:28 |
Сообщение № 14

Группа: Модераторы

Ранг: Старожил

Сообщений: 2198


Репутация:

898

±

Замечаний:
0% ±


Excel 2010, 2016

Вот еще вариант (где нашла, уже не помню), вдруг подойдет:
[vba]

Код

Declare Function WNetGetUserA Lib «mpr.dll» (ByVal lpName As String, ByVal lpUserName As String, lpnLength As Long) As Long

[/vba][vba]

Код

Function GetUserName() As String
       Dim sUserNameBuff As String * 255
       sUserNameBuff = Space(255)
       Call WNetGetUserA(vbNullString, sUserNameBuff, 255&)
       GetUserName = Left$(sUserNameBuff, InStr(sUserNameBuff, vbNullChar) — 1)
End Function
Sub tt()
MsgBox GetUserName
End Sub

[/vba]
и еще тут есть пример, правда по-моему тоже самое, что и я написала


ЯД: 410013299366744 WM: R193491431804

 

Ответить

EvgenyD

Дата: Вторник, 01.09.2015, 22:39 |
Сообщение № 15

Группа: Пользователи

Ранг: Участник

Сообщений: 74


Репутация:

19

±

Замечаний:
0% ±


Excel 2013

Manyasha, спасибо это уже пробовал. Увы, выдает «Евгений», а хотелось бы то, что я в сообщении №4 прикреплял.

 

Ответить

anvg

Дата: Среда, 02.09.2015, 08:39 |
Сообщение № 16

Группа: Друзья

Ранг: Ветеран

Сообщений: 581


Репутация:

271

±

Замечаний:
0% ±


2016, 365

Доброе время суток
Скорее всего предложенными средствами так или иначе возвращается имя пользователя, вошедшего в систему Windows. Вам же нужна данные учётной записи подключения к Office 365. Скорее всего в объектной модели Excel такого нет (Может что есть в объектной модели Microsoft Office Object Library). Можно попытаться, используя Using Excel to Retrieve Office 365 Reporting Data — хотя есть вопрос — захотите ли вы светить данные входа администратора Offce 365, получить информацию если она там есть о подключенных пользователях и, если есть, с какого компьютера они подключены. Увы, сообщить что-то детальнее не могу — не имею установленного Office 365.

Цитата

HKEY_USERSS-1-5-21-1838117663-2728108920-1439421766-1000SoftwareMicrosoftOffice15.0CommonIdentityIdentitiesdc7cdd78f0fa498e_OrgId

Интересно, а в ветке залогиневшегося к Office 365 текущего пользователя Windows HKEY_CURRENT_USERSoftwareMicrosoftOffice15.0CommonIdentityIdentities — ничего нет?

Сообщение отредактировал anvgСреда, 02.09.2015, 08:46

 

Ответить

EvgenyD

Дата: Среда, 02.09.2015, 09:15 |
Сообщение № 17

Группа: Пользователи

Ранг: Участник

Сообщений: 74


Репутация:

19

±

Замечаний:
0% ±


Excel 2013

anvg, Вы правы, по этому пути находятся такие же данные как и в указанном мной ранее.
Приведенную статью еще не читал, сяду вечером, т.к. это надолго (с инглишем плохо).

 

Ответить

anvg

Дата: Среда, 02.09.2015, 11:07 |
Сообщение № 18

Группа: Друзья

Ранг: Ветеран

Сообщений: 581


Репутация:

271

±

Замечаний:
0% ±


2016, 365

Цитата

по этому пути находятся такие же данные

Не могли бы вы скинуть экспортированную ветку этого раздела реестра, естественно, изменив сами имена, логины, в силу их конфиденциальности? Вдруг там есть какой-нибудь идентификатор активного пользователя, тогда требуемую информацию можно будет попытаться извлечь из реестра.
Если будете экспортировать, то сделайте это при запущенном Excel и выполненном входе в учётную запись Microsoft.

 

Ответить

anvg

Дата: Среда, 02.09.2015, 21:25 |
Сообщение № 19

Группа: Друзья

Ранг: Ветеран

Сообщений: 581


Репутация:

271

±

Замечаний:
0% ±


2016, 365

Можно таким кодом
[vba]

Код

Private Const IdentitiesSubKeyName As String = «SoftwareMicrosoftOffice15.0CommonIdentityIdentities»
Private Function GetIdentitiesNames()
On Error GoTo errHandle
      Const HKEY_CURRENT_USER = &H80000001
      Dim pReg As Object, sNames
      Set pReg = GetObject(«winmgmts:{impersonationLevel=impersonate}!\.rootdefault:StdRegProv»)
      pReg.EnumKey HKEY_CURRENT_USER, IdentitiesSubKeyName, sNames
      GetIdentitiesNames = sNames
Exit Function
errHandle:
      GetIdentitiesNames = sNames
End Function

Public Sub test()
      Const SignParamName = «SigninName», DisplayParamName = «FriendlyName»
      Dim Keys, i As Long, SignName As String, DisplayName As String
      Dim wshShell As Object, sKey As String
      Keys = GetIdentitiesNames
      If Not IsEmpty(Keys) Then
          Set wshShell = CreateObject(«WScript.Shell»)
          For i = LBound(Keys) To UBound(Keys)
              sKey = Keys(i)
              SignName = wshShell.RegRead(«HKCU» & IdentitiesSubKeyName & «» & sKey & SignParamName)
              DisplayName = wshShell.RegRead(«HKCU» & IdentitiesSubKeyName & «» & sKey & DisplayParamName)
              Debug.Print SignName & » === » & DisplayName
          Next
      End If
End Sub

[/vba]
Но остаются два невыясненных вопроса
1. Позволит ли код обратиться к реестру, если это обычный пользователь (если wmi запрещено, то однозначно нет)?
2. Что будет в реестре, если пользователь из под одной учётки Windows более одного раза за сессию подключался к Office 365 под разными именами входа?

Сообщение отредактировал anvgСреда, 02.09.2015, 21:27

 

Ответить

EvgenyD

Дата: Четверг, 03.09.2015, 11:22 |
Сообщение № 20

Группа: Пользователи

Ранг: Участник

Сообщений: 74


Репутация:

19

±

Замечаний:
0% ±


Excel 2013

anvg, на Вашем решении и остановлюсь.
Протестировал на 5 машинах пользователей. (Все ОС — Win7, MS Office 365 Business)
При смене учетки, смена значений происходит только после перезапуска приложения (данные в реестр записываются при корректном выходе из приложения, на сколько я понимаю). По пункту 1 протестировать нет возможности.
Прикрепляю файлик с Вашим решением, для возможности быстро попробовать, может еще кто-то протестирует.

 

Ответить

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

This article will show you how to create a login UserForm using Excel VBA.

VBA-Login

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.

Admin Sheet

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.

Name Range

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.

Add 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.

Open VBA Editor

  • From the “Insert” tab, insert “UserForm.”

Insert Userform

  • It will create a new UserForm like the below one.

Userform

  • Press the F4 key to see the “Properties” window. From this window, change the name of the UserForm to “LogInUF.”

vba log in - Change Userform Name

  • 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.

vba log in - Userform Properties

  • Now, my UserForm looks like this.

vba log in - Userform Edited

Step 2: Design Userform

  • From the toolbox of the UserForm, insert two label boxes and enter the text, as shown below.

vba log in - Add Labels

  • From the toolbox, insert “Combo Box.”

vba log in - Add ComboBox

  • 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.

vba log in - Change ComboBox Name

  • From the “RowSource” property of the combo box, enter the name given to the zone list in the “Admin Sheet.”

Excel vba log in - ComboBox Add Row Source

  • 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.

Excel vba log in - ComboBox Drop-Down List

  • For “Enter Your Password,” we need to insert a “Text Box” from the toolbox.

Excel vba log in - Insert TextBox

  • For this “Text Box,” we need to change the “Name” property and change it as “Password_TB.”

vba log in - Change TextBox Name

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.”

vba log in - Add CommandButton

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.

vba log in - Log in Button

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

vba log in - Log out Button

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

Log in - Userform Code

  • 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.

Thisworkbook

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

Log in - Thisworkbook Code

  • 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.

vba login form

  • 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.

vba login form for East

  • If we click “Log In,” we can see only the “East” zone worksheet.

VBA Login East Zone Data

Similarly, if we log in with “Admin,” we can access all the worksheets.

VBA Login with Admin

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

VBA Login

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.

VBA Login Example 1

Step 2: Now once we get the UserForm opened, from the toolbox select the Label option and create a label box in Userform.

VBA Login Example 1-2

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.

VBA Login Example 1-3

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.

VBA Login Example 1-4

Step 5: Now we will create a text box here to enter the user name for login as shown below.

VBA Login Example 1-5

Step 6: Now we would insert a label for entering the password.

VBA Login Example 1-6

Step 7: Again we would change the name of Label, color, font, size, and name as required below.

Properties window Example 1-7

Step 8: Insert a text box for entering the password against the Password label.

Text Box Example 1-8

Step 9: And last, create a login button with the help of the Command button to click on it.

Command button Example 1-9

Step 10: Now edit the properties of created Command Button from the Properties window at left.

Properties window Example 1-10

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

VBA Login Example 1-11

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

IF – End IF loop Example 1-12

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.

VBA Login Example 1-13

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

VBA Login Example 2-1

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

Else If condition Example 2-2

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

VBA Login Example 2-3

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

CommandButton2 Example 2-4

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

Quit Application Example 2-5

Step 6: Final would look like this below.

VBA Login Example 2-6

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.

VBA Login Example 2-7

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 –

  1. VBA Name Worksheet
  2. VBA Input
  3. VBA Solver
  4. 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.

  1. System Environment Variables – Windows login user
  2. Application.username – MS Office user name
  3. Windows API ‘apiGetUserName’ Function
  4. Network UserName
  5. 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

Excel VBA Get Username Settings in Menu

Excel VBA Get Username Settings in Menu

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.

Понравилась статья? Поделить с друзьями:
  • Vba excel формат времени в ячейке
  • Vba excel установить текущую ячейку
  • Vba excel установить курсор в textbox
  • Vba excel форма с кнопками
  • Vba excel установить значение ячейки