如何在Access VBA中获取当前登录的Windows用户?

时间:2008-10-03 20:07:36

标签: winapi ms-access access-vba

我是通过谷歌发现的:http://www.mvps.org/access/api/api0008.htm

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

这是最好的方法吗?

6 个答案:

答案 0 :(得分:12)

你也可以这样做:

Set WshNetwork = CreateObject("WScript.Network")
Print WshNetwork.UserName

它还有一个UserDomain属性和许多其他东西:

http://msdn.microsoft.com/en-us/library/907chf30(VS.85).aspx

答案 1 :(得分:6)

您也可以使用Environ $,但问题指定的方法更好。用户/应用程序可以更改环境变量。

答案 2 :(得分:2)

我通常在VBA中使用environ,如下所示。我没有把Ken提到的问题作为可能性。

Function UserNameWindows() As String
    UserNameWindows = VBA.Environ("USERNAME") & "@" & VBA.Environ("USERDOMAIN")
End Function

答案 3 :(得分:1)

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

答案 4 :(得分:1)

其他帖子中有很多替代方法,但要回答这个问题:是的,这是最好的方法。如果您想要的只是用户名,则可以比创建COM对象或WMI更快,并且可以在Win95的所有Windows版本中使用。

答案 5 :(得分:0)

有很多方法可以在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

有关详细信息,请查看以下链接:
http://msdn.microsoft.com/en-us/library/aa394599%28v=vs.85%29.aspx

相关问题