Содержание
- Application.UserName property (Project)
- Syntax
- Remarks
- Example
- Support and feedback
- Свойство Application.UserName (Project)
- Синтаксис
- Примечания
- Пример
- Поддержка и обратная связь
- Get and Change User Name with VBA
- Get and Change Application User Name in VBA
- Get User Name
- Change User Name
- VBA Coding Made Easy
- VBA Code Examples Add-in
- Excel VBA Get Username – 6 Easy Ways using Macro
- Different Method to Find Windows UserName
- 1. Insert Windows Username in Excel Cell
- 2. VBA Application.Username – Excel User
- 3. Excel VBA Get Username from System Environment Variables
- 4. Using Windows API ‘apiGetUserName’ Function
- 5. Network UserName in Excel VBA
- 5.1. From Windows Registry
- UserName Property of Application Object VBA
- VBA Reference
- 120+ Project Management Templates
- VBA UserName Application Property – Syntax
- VBA UserName Application Property: Example 1
- VBA UserName Application Property – Instructions
Application.UserName property (Project)
Gets or sets the local name of the current user. Read/write String.
Syntax
expression.UserName
expression A variable that represents an Application object.
The UserName property of the Application object shows the local user name. By comparison, the UserName property of the Profile object shows the logon name.
Use the UserName property to customize Project options or macros for a particular user. For example, suppose you have written a macro named PrintReport that prints the Mine.mpp report when you press CTRL+R, but another user wants to use the same shortcut keys to print the Yours.mpp report. You can edit the PrintReport macro so that it checks the UserName property and then prints Mine.mpp if you are the current user or prints Yours.mpp if you are not the current user.
The UserName property is the local name but can be changed to a different value. The Author field in the Project Properties dialog box is the logon name of the user by default.
Example
The following example sets preferences according to the name of the current user.
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Свойство Application.UserName (Project)
Возвращает или задает локальное имя текущего пользователя. Для чтения и записи, String.
Синтаксис
expression. Пользователя
выражение: переменная, представляющая объект Application.
Примечания
В свойстве UserName объекта Application отображается имя локального пользователя. Для сравнения в свойстве UserName объекта Profile отображается имя входа.
Используйте свойство UserName для настройки параметров проекта или макросов для конкретного пользователя. Например, предположим, что вы написали макрос с именем PrintReport , который печатает отчет Mine.mpp при нажатии клавиш CTRL+R, но другой пользователь хочет использовать те же сочетания клавиш для печати отчета Yours.mpp. Макрос PrintReport можно изменить так, чтобы он проверял свойство UserName, а затем выводит Mine.mpp, если вы являетесь текущим пользователем, или yours.mpp, если вы не являетесь текущим пользователем.
Свойство UserName является локальным именем, но его можно изменить на другое значение. Поле «Автор» в диалоговом окне «Свойства проекта» по умолчанию представляет собой имя пользователя для входа.
Пример
В следующем примере задаются параметры в соответствии с именем текущего пользователя.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Get and Change User Name with VBA
In this Article
This short tutorial will demonstrate how to use the Application.UserName method.
Get and Change Application User Name in VBA
Get User Name
You can use Application.UserName for returning or setting the name of the current user. This is the default name that shows in “macro recorded by”, new comments, “last saved by” etc..
You can display the current user’s name in a message box like this:
Change User Name
You can change the current user name like this:
If you are interested who is the author of the current workbook, you can get it like this:
You can also change it:
Windows user name can be obtained like this:
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
Excel VBA Get Username – 6 Easy Ways using Macro
Please enable JavaScript
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?
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.
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.
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.
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.
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.
All these combination of codes, fetch current Windows user name details to Excel.
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.
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.
External References
Источник
UserName Property of Application Object VBA
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
50+ Excel Templates
50+ PowerPoint Templates
25+ Word Templates
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
UserName Application Property in VBA is used to sets or returns the name of the user. Please find the more details about UserName in the following section.
VBA UserName Application Property – Syntax
Here syntax for UserName Property of application object in VBA.
Where UserName as String.
In the above syntax Application represents object and UserName is the Property of Application object.
VBA UserName Application Property: Example 1
Please find the below example for UserName Property of application object in excel VBA. The below example displays the user name of the application.
VBA UserName Application Property – Instructions
Please follow the below steps to execute the VBA code to save the excel file.
Step 1: Open any existing Excel Application.
Step 2: Press Alt+F11 – This will open the VBA Editor.
Step 3: Insert a code module from then insert menu.
Step 4: Copy the above code and paste in the code module which have inserted in the above step.
Step 5: Now press F5 to execute the code.
Источник
In most of the online resource I can find usually show me how to retrieve this information in VBA. Is there any direct way to get this information in a cell?
For example as simple as =ENVIRON('User')
(which did not work)
Deduplicator
44.3k7 gold badges65 silver badges115 bronze badges
asked Aug 3, 2011 at 22:41
Anthony KongAnthony Kong
36.7k44 gold badges169 silver badges297 bronze badges
Without VBA macro, you can use this tips to get the username from the path :
=MID(INFO("DIRECTORY"),10,LEN(INFO("DIRECTORY"))-LEN(MID(INFO("DIRECTORY"),FIND("",INFO("DIRECTORY"),10),1000))-LEN("C:Users"))
answered Dec 10, 2018 at 10:16
1
if you don’t want to create a UDF in VBA or you can’t, this could be an alternative.
=Cell("Filename",A1)
this will give you the full file name, and from this you could get the user name with something like this:
=Mid(A1,Find("",A1,4)+1;Find("";A1;Find("";A1;4))-2)
This Formula runs only from a workbook saved earlier.
You must start from 4th position because of the first slash from the drive.
answered Mar 22, 2016 at 19:34
1
This displays the name of the current user:
Function Username() As String
Username = Application.Username
End Function
The property Application.Username
holds the name entered with the installation of MS Office.
Enter this formula in a cell:
=Username()
answered Nov 20, 2017 at 19:08
rolacherrolacher
681 silver badge4 bronze badges
2
Example: to view the Windows User Name on Cell C5, you can use this script:
Range("C5").Value = ": " & Environ("USERNAME")
Nickolay
30.6k12 gold badges106 silver badges181 bronze badges
answered Sep 28, 2012 at 2:04
web solusiweb solusi
591 silver badge1 bronze badge
The simplest way is to create a VBA macro that wraps that function, like so:
Function UserNameWindows() As String
UserName = Environ("USERNAME")
End Function
Then call it from the cell:
=UserNameWindows()
See this article for more details, and other ways.
answered Aug 3, 2011 at 22:51
Lance RobertsLance Roberts
22.2k32 gold badges112 silver badges129 bronze badges
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Application.UserName property (Excel) |
vbaxl10.chm133225 |
vbaxl10.chm133225 |
excel |
Excel.Application.UserName |
6cb2636c-ef3c-82fb-583d-8390cc815631 |
04/05/2019 |
medium |
Application.UserName property (Excel)
Returns or sets the name of the current user. Read/write String.
Syntax
expression.UserName
expression A variable that represents an Application object.
Example
This example displays the name of the current user.
MsgBox "Current user is " & Application.UserName
[!includeSupport and feedback]
Ниже привел часть кода, который сохраняет книгу под определенным именем в папку «разное» на рабочем столе. nm и naz — ранее обозначенные переменные. Проблема в следующем: при переносе исходного файла на другой комп и запуске кода у некоторых пользователей все ОК, а у многих других выдается ошибка в строке, содержащей переменную un. Стоит заменить переменную на имя — все ОК.
Может кто знает — какая икселю разница, почему как-то выборочно действует (если уж ошибка, так пусть бы везде и у всех…ан нет) и как это забороть? Можно конечно сохранять на диск или папку «разное» создать на самом диске, чтоб с Application.UserName не париться, но интересно, чего не работает-то?
un = Application.UserName
nnm = nm + «_» + naz
ChDir «C:Documents and Settings» & (un) & «Desktopразное»
ActiveWorkbook.SaveAs Filename:= _
«C:Documents and Settings» & (un) & «Desktopразное» & (nnm) & «.xls» _
, FileFormat:=xlNormal, Password:=»», WriteResPassword:=»», _
ReadOnlyRecommended:=False, CreateBackup:=False
-
#2
They are not the same. Change it in Excel’s settings if you want the same for that part anyway.
-
#3
Ken, I want them to be different. When i use 2007, it shows Pediez for environ(«username») and application.username shows Pedie Nz
I want it to be that way even in excel 2003.
Is there any way to handle this?
-
#4
As previous poster said change it in Tools>Options you should be able to set the name you want.
Application Username is the name of the User set in Excel Tools>Options
Environ(«Username») is the name you registered for Windows see Control Panel >System
-
#5
Application Username is okay, that appears as it has to be. But Environ(«Username») should appear different that is what i’m looking to do
I dont understand why it is not showing as it should i mean the Environ(«Username»)….i mean in 2003.
-
#6
Application Username is okay, that appears as it has to be. But Environ(«Username») should appear different that is what i’m looking to do
I dont understand why it is not showing as it should i mean the Environ(«Username»)….i mean in 2003.
You aren’t understanding.
Environ(«username») is the user name which you log into Windows with.
Application.UserName is the user name which is set by the user when they run the program for the first time or whatever it was if you go to TOOLS > OPTIONS > GENERAL and set it under User Name.
For some business installs you may have had the Application.Username set by the IT folks to be the default of your Windows Login. If so you can go change it in the application.
-
#7
Open the Control panel and launch System Note the registered Name.
Open Excel 2003 and find the user name
Open Excel 2007 and find the user name
Excel will be different Match them up.
-
#8
I hope that the difference is clear now. It is easy to confuse the two.
It is easy to change the username in the Excel Application. Anyone using your computer can do it. Do my the menu method as was explained or by code.
e.g. In the Immediate Window of the VBE. Insert your name in place of mine and press Enter key after each line inserted separately:
Code:
Application.UserName="John Doe"
?Application.UserName
Application.UserName="Kenneth Hobson"
?Application.UserName
It is not so easy to do for the Windows username. Basically, you have to add a new user profile for a new Windows username and then log onto that account.
A few easy ways to see your Windows username as given by Environ(«username»).
1. In the VBE immediate window, type: ?Environ(«username»), and press the enter key.
2. Click Start button, Run, and type: %username%, and press Enter key or OK.
3. Start > Run > cmd > OK > Set Username > press Enter key > Exit.
a. If you type, Set, and press Enter key after cmd above, you can see all of the environment variables and values.
Last edited: Oct 29, 2010
-
#9
Thanks for explaining things in detail…
Have a great Weekend!
-
#10
It is not so easy to do for the Windows username.
Actually, sadly it is VERY EASY to do. Try this out Kenneth — run this code:
Code:
Environ("username") = "Silly One"
and then check to see what your user name comes back as when you use Environ(«username»).
That is why most of us developers actually prefer using the Windows API because that CANNOT be manipulated like that.