Last active
May 30, 2018 15:42
-
-
Save mjdescy/5b14043d0c3f3bb1e12f4046a0eb96db to your computer and use it in GitHub Desktop.
VBA Module to Get Logged In User Name from Windows API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Attribute VB_Name = "LoggedInUserName" | |
Option Explicit | |
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _ | |
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long | |
Function GetLoggedInUserName() As String | |
Dim MaxBufferLength As Long | |
MaxBufferLength = 255 | |
Dim UserNameBuffer As String | |
UserNameBuffer = String$(MaxBufferLength - 1, 0) | |
Dim APIResult As Long | |
APIResult = apiGetUserName(UserNameBuffer, MaxBufferLength) | |
If (APIResult > 0) Then | |
GetLoggedInUserName = Left$(UserNameBuffer, MaxBufferLength - 1) | |
Else | |
GetLoggedInUserName = vbNullString | |
End If | |
End Function | |
Public Sub UnitTest_LoggedInUserName() | |
Debug.Print GetLoggedInUserName() | |
End Sub |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT GetLoggedInUserName() AS UserName | |
FROM [UserTable]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The function
GetLoggedInUserName
will return the logged in user's username, using the Windows API. The API call far less likely to be spoofed than the otherwise comparable method of reading theUSERNAME
environment variable viaEnviron("USERNAME")
.GetLoggedInUserName
is defined in a module, rather than a class, so the function is accessible in queries, such as in "UserName.sql".If you wish to look up the username for use in a Data Macro, you need to:
GetLoggedInUserName
and selects from an actual table that returns at least one row. For example: "UserName.sql".LookupRecord
macro step that calls the SQL query.SetLocalVar
macro step within theLookupRecord
group that stores the SQL query column into a local variable.