Tuesday, March 1, 2011

Excel 2007 VBA and WMI - Current DOMAIN\USER

I was wondering if there was a simple way to use WMI to get you the current windows user name with domain. The Windows API call just gets you the short username, so you end up doing another call for the domain name. I have some code, but I get an automation error. Any ideas? I think I'm on the right path, but I am a little new to WMI.

Function GetFullName() As String
    Dim computer As String
    computer = "."
    Dim objWMIService, colProcessList As Object
    Set objWMIService = GetObject("winmgmts:\\" & computer & "\root\cimv2")
    Set colProcessList = objWMIService.ExecQuery _
        ("SELECT TOP 1 * FROM Win32_Process WHERE Name = 'EXCEL.EXE'")
    Dim uname, udomain As String
    Dim objProcess As Object
    For Each objProcess In colProcessList
        objProcess.GetOwner uname, udomain
    Next
    GetFullName = UCase(udomain) & "\" & UCase(uname)
End Function

UPDATE: see comments on accepted answer

From stackoverflow
  • There is no TOP 1 clause in WQL. Leave it out and your query should work:

    "SELECT * FROM Win32_Process WHERE Name = 'EXCEL.EXE'"
    
    tyndall : What if someone else is logged into the box on another account? Does this strategy fall apart? Could it pick up the Excel that the other user might be running and return the incorrect info? btw, removing the TOP 1 worked.
    Uros Calakovic : Yes it does. In case of multiple Excel.exe instances started by different users, the function would return uname and udomain for the last objProcess enumerated, which would not necessarily be the instance that called it. It would be easy if Excell.Application had a property for ProcessId...
  • How about

    UserName = Environ("Username")
    Domain = Environ("UserDomain")
    Combined= Environ("UserDomain") & "\" & Environ("Username")
    
    Remou : Note that Environ is an "unsafe expression" in sandbox mode: http://office.microsoft.com/en-us/access/HA012301901033.aspx?pid=CH100621891033
    tyndall : Also, people can change their environment variables right?

0 comments:

Post a Comment