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.
我想知道是否有一种简单的方法来使用WMI来获取当前具有域的Windows用户名。 Windows API调用只会获得短用户名,因此您最终会再次调用域名。我有一些代码,但是我遇到了自动化错误。有任何想法吗?我认为我走的是正确的道路,但我对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
更新:请参阅有关已接受答案的评论
3 个解决方案
#1
1
There is no TOP 1 clause in WQL. Leave it out and your query should work:
WQL中没有TOP 1子句。保留它,你的查询应该工作:
"SELECT * FROM Win32_Process WHERE Name = 'EXCEL.EXE'"
#2
2
How about
UserName = Environ("Username")
Domain = Environ("UserDomain")
Combined= Environ("UserDomain") & "\" & Environ("Username")
#3
2
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:
意识到这是旧的,但是为了处理多个excel实例,另一篇文章(下面链接)阐明了如何获取当前应用程序的进程ID:
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?
如何在不使用标题的情况下通过VBA获取当前Excel实例的进程ID?
#1
1
There is no TOP 1 clause in WQL. Leave it out and your query should work:
WQL中没有TOP 1子句。保留它,你的查询应该工作:
"SELECT * FROM Win32_Process WHERE Name = 'EXCEL.EXE'"
#2
2
How about
UserName = Environ("Username")
Domain = Environ("UserDomain")
Combined= Environ("UserDomain") & "\" & Environ("Username")
#3
2
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:
意识到这是旧的,但是为了处理多个excel实例,另一篇文章(下面链接)阐明了如何获取当前应用程序的进程ID:
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?
如何在不使用标题的情况下通过VBA获取当前Excel实例的进程ID?