Share via

Require MS Excel VBA code to retrieve current userID

Pritesh Thakker 0 Reputation points
2025-12-17T08:30:01.2666667+00:00

For personal and office use, I need to have Excel VBA code that can help me fetch / see current system userID that is using the Excel file, thereby thereafter I will be filtering file content to show only relevant data to that user

I hope my query is clear and someone can please help me

Microsoft 365 and Office | Excel | Other | Windows
0 comments No comments

1 answer

Sort by: Most helpful
  1. AI answer

    2025-12-17T08:30:20.06+00:00

    To retrieve the current user ID in Excel using VBA, you can utilize the Windows API function GetUserNameA. Below is a sample code snippet that demonstrates how to implement this in your Excel VBA environment:

    Declare PtrSafe Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
    
    Function GetLogonName() As String
        Dim buffer As String * 255
        Dim size As Long
        size = 255
        If GetUserName(buffer, size) Then
            GetLogonName = Left(buffer, InStr(buffer, Chr(0)) - 1)
        Else
            GetLogonName = ""
        End If
    End Function
    
    Sub ShowCurrentUser()
        MsgBox "Current User ID: " & GetLogonName()
    End Sub
    

    Explanation:

    1. Declare Function: This line declares the GetUserName function from the advapi32.dll library, which is used to get the username of the logged-in user.
    2. GetLogonName Function: This function calls GetUserName, retrieves the username, and returns it as a string.
    3. ShowCurrentUser Sub: This subroutine displays the current user ID in a message box.

    You can call the ShowCurrentUser subroutine to see the current user ID when you run the code in your Excel VBA environment.


    References:

    AI-generated content may be incorrect. Read our transparency notes for more information.

    Was this answer helpful?

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.