VBA: How to get the account login user name and the account full name for a program (ex: Microsoft Word)

If you need to retrieve the [ user name ] and [ full name ] fields of the account under which a program is running, you can use the code listed below. The sample VBA routine also works for domain user accounts.



[Make sure you include the following reference in your VBA project before running this code: 'Active DS Type Library (C:\Windows\System32\activeds.tlb)' ]

Sub saveUser()

 Dimcomputer As String
computer = "."

Dim  objWMIService, colProcessList As Object
Set objWMIService = GetObject( "winmgmts:\\" & computer & "\root\cimv2" )
   colProcessList = objWMIService.ExecQuery( "SELECT * FROM Win32_Process WHERE Name = 'WINWORD.EXE'" )

 Dim uname, udomain As String
Dim objProcess         As Object
For Each objProcess In colProcessList

    objProcess.GetOwner uname, udomain

                ‘if multiple instances of Word run in background you should save the user name and domain for each one
‘or insert a break here
Dim User As ActiveDs.IADsUser
Dim domainname As String

domainname = udomain


Str As String
Str = "WinNT://" & domainname & "/" & uname & ",user"

 Set User = GetObject( Str )

 If Err.Number <> 0 Then
MsgBox "Domain or User does not exist."
    Exit Sub End If

 If User.FullName = "" Then
   MsgBox User.Name
   MsgBox User.FullName
End If

End Sub