使用 WMI 在 VBA 中获取当前的 Windows 用户名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/287369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 10:03:27  来源:igfitidea点击:

Use WMI to get current Windows username in VBA

excelexcel-vbaautomationwmiusernamevba

提问by BuddyJoe

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

更新:查看对已接受答案的评论

采纳答案by BuddyJoe

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'"

回答by dbb

How about

怎么样

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

回答by Russ

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?