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

ada*_*box 9 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 **************************
Run Code Online (Sandbox Code Playgroud)

这是最好的方法吗?

bob*_*olt 12

你也可以这样做:

Set WshNetwork = CreateObject("WScript.Network")
Print WshNetwork.UserName
Run Code Online (Sandbox Code Playgroud)

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

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


Ken*_*Ken 6

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