Use WMI to get current Windows username in VBA

跟風遠走 提交于 2019-12-24 12:06:06

问题


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


回答1:


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

"SELECT * FROM Win32_Process WHERE Name = 'EXCEL.EXE'"



回答2:


How about

UserName = Environ("Username")
Domain = Environ("UserDomain")
Combined= Environ("UserDomain") & "\" & Environ("Username")



回答3:


Realize this is old, but to deal with multiple excel instances, another post (linked below) clarifies how to get the process Id of the current application with:

Declare Function GetCurrentProcessId Lib "kernel32" () As Long
...
ProcessID = GetCurrentProcessId

Set ColProcessIDList = objWMIService.ExecQuery( _
    "SELECT * FROM Win32_Process WHERE ProcessID = '" & ProcessID & "'")
...

How to get the process ID of the current Excel instance, through VBA, without using the caption?



来源:https://stackoverflow.com/questions/287369/use-wmi-to-get-current-windows-username-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!