|
|
|
|
|
|
Excel
|
Getting the Username
|
|
Ease of Use
|
Easy
|
Version tested with
|
2000, 2002
|
Submitted by:
|
Justinlabenne
|
Description:
|
Shows different ways to obtain the username
|
Discussion:
|
This code shows 4 different way to obtain the current username. Useful if you need a consistent way to tell who is currently logged in. Application.Username only returns the name used for the application, and in many companies the name can be a default "Company User" or something similiar. Using api, the wscript.network object, or the Environ function, you can obtain the actual name of the user who is logged into Windows. The example file contains example for each: api, environ, wscript, and the application.
Another way of getting the username is listed here: http://vbaexpress.com/kb/getarticle.php?kb_id=234
|
Code:
|
instructions for use
|
Option Explicit
Private Declare Function GetUserName& Lib "advapi32.dll" Alias "GetUserNameA" _
(ByVal lpBuffer As String, _
nSize As Long)
Public Function WindowsUserName() As String
Dim szBuffer As String * 100
Dim lBufferLen As Long
lBufferLen = 100
If CBool(GetUserName(szBuffer, lBufferLen)) Then
WindowsUserName = Left$(szBuffer, lBufferLen - 1)
Else
WindowsUserName = CStr(Empty)
End If
End Function
Sub GetTheNameAPI()
MsgBox "Network username is: " & WindowsUserName
End Sub
Sub GetTheNameAPP()
MsgBox "Application username is: " & Application.UserName
End Sub
Sub GetTheNameENVIRON()
MsgBox "Environ username is: " & Environ("USERNAME")
End Sub
Sub GetTheNameNETWORK()
Dim objNet As Object
On Error Resume Next
Set objNet = CreateObject("WScript.NetWork")
MsgBox "Network username is: " & objNet.UserName
Set objNet = Nothing
End Sub
|
How to use:
|
- Open an Excel Workbook
- Copy the code
- Press Alt + F11 to open the Visual Basic Editor (VBE)
- Select INSERT > MODULE from the menubar
- Paste code into the right pane
- Press Alt+Q to return to Excel
- Save workbook before any other changes
|
Test the code:
|
- Go to TOOLS > MACRO > MACROS
- When the dialog appears, select (GetTheNameAPI)
- Press Run
- Go to TOOLS > MACRO > MACROS
- When the dialog appears, select (GetTheNameAPP)
- Press Run
- Go to TOOLS > MACRO > MACROS
- When the dialog appears, select (GetTheNameENVIRON)
- Press Run
|
Sample File:
|
Getting the Username.zip 8.52KB
|
Approved by mdmackillop
|
This entry has been viewed 452 times.
|
|