home

Obtain Windows Login

February 12th 2003

This explains how to obtain the user name with which the user is logged into the Windows Network. One way to obtain the user name is the function Environ("username"). The other is this method which I obtained from Dev Ashish's site.


Option Compare Database
' 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 http://www.mvps.org/access/api/api0008.htm
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

Save this module and name it something like modWindowsLoginName. Then, the function for returning this value in code would be fOSUserName().