如何在Access VBA中获取当前登录的Windows用户?
问题描述:
我通过谷歌发现这一点:http://www.mvps.org/access/api/api0008.htm如何在Access VBA中获取当前登录的Windows用户?
'******************** Code Start **************************
' This code was originally written by Dev Ashish.
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
'
' Code Courtesy of
' Dev Ashish
'
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Function fOSUserName() As String
' Returns the network login name
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)
If (lngX > 0) Then
fOSUserName = Left$(strUserName, lngLen - 1)
Else
fOSUserName = vbNullString
End If
End Function
'******************** Code End **************************
这是做的最好的方法是什么?
答
您也可以使用Environ $,但问题指定的方法更好。用户/应用程序可以更改环境变量。
答
Alternative way要做到这一点 - 可能你提到的API是获取用户名的更好方法。
For Each strComputer In arrComputers
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)
For Each objItem in colItems
Wscript.Echo "UserName: " & objItem.UserName & " is logged in at computer " & strComputer
Next
答
你也可以这样做:
Set WshNetwork = CreateObject("WScript.Network")
Print WshNetwork.UserName
它也有一个用户网域特性和一堆其他的东西:
http://msdn.microsoft.com/en-us/library/907chf30(VS.85).aspx
答
我一般使用ENVIRON从内部VBA如下所述。我没有把肯提到的问题视为可能性。
Function UserNameWindows() As String
UserNameWindows = VBA.Environ("USERNAME") & "@" & VBA.Environ("USERDOMAIN")
End Function
答
很多其他方法的替代方法,但要回答这个问题:是的,这是做到这一点的最好方法。比创建COM对象或WMI更快,如果你想要的只是用户名,并且可以从Win95以上的所有版本的Windows中使用。
答
有很多方法可以在WMI中获取当前记录的用户名。 我的方法是通过“explorer.exe”进程的用户名 获取它,因为当用户登录到窗口时,根据当前用户访问此文件。
WMI脚本会是这样的:
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strIP & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process")
For Each objprocess In colProcessList
colProperties = objprocess.GetOwner(strNameOfUser, strUserDomain)
If objprocess.Name = "explorer.exe" Then
UsrName = strNameOfUser
DmnName = strUserDomain
End If
Next
更多detailcheck链接:
http://msdn.microsoft.com/en-us/library/aa394599%28v=vs.85%29.aspx
这个问题几乎是完全相同的副本http://*.com/questions/9052的/ is-there-a-way-for-ms-access-to-grab-the-current-active-directory-user – Yarik 2008-11-03 09:31:27
[有没有办法让MS Access抓取当前的Active Directory用户?] http://*.com/questions/9052/is-there-a-way-for-ms-access-to-grab-the-current-active-directory-user) – 2017-04-07 06:22:25