excelvbawindowsactive-directory

Is there any way to get VBA to get the current user's Full Name from a Windows user account without using CMD?


Is there any way to get VBA to get the current user's Full Name from a Windows user account without using CMD?

I have a team who all work collaboratively on Excel files on Windows machines. We are on a domain but cannot use OneDrive to work collaboratively.

To help keep track of edits I have written some VBA to record a timestamp and current user on each save (below).

Environ("Username") returns their Windows Username, which is something like ID1234. I know that all users are configured to have a Full Name like (Company) Flash Steel associated with their user account.

The Full Name is much more useful for record keeping.

I have used a previous answer calling 'net user' in CMD.exe and parsing the SDTOUT. This works but I was hoping for something more elegant and hopefully called natively in VBA.

' When saving, append the user ID and timestamp
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    ...
    Worksheets("Front Cover").Range(nextTimestampCell).Value = Format(Now(), "yy/mm/dd - HH:nn:ss")
    ' Build string for command
    cMDcommand = "cmd /c net user """ & Environ("Username") & """ /DOMAIN | find /I ""Full name"""
    ' Execute command and read top line
    result = Trim(CreateObject("Wscript.Shell").Exec(cMDcommand).StdOut.readline)
    ' Trim result and output User
    Worksheets("Front Cover").Range(nextUserCell).Value = Right(result, Len(result) - 29)
End Sub

Solution

  • Since you're working in Excel, perhaps use Application.UserName:

    Worksheets("Front Cover").Range(nextUserCell).Value = Application.UserName