M.9. Determine the User Name

Often, you'll need to know the current user of the application. This might be to determine what activities they are allowed to do or to stamp records with change logging information. There are two user names that you'll be concerned with: the current Access user and the current Windows user.

M.9.1. The Current Access User

The current Access user is determined using the built-in CurrentUser function. However, if you are not using Access security and requiring the user to log in with a User Name and Password, this user name will always be the default Access user of Admin. Because this isn't too descriptive, you may need to know the name of the user that is currently using this PC.

M.9.2. The Current Windows User

To determine the currently logged in Windows user, you can use this code. First, in the module declaration section, include this code:

Global Const ERRORMOREDATA = 234
Global Const ERR_SUCCESS = 0

Private Declare Function WNetGetUser Lib "mpr" Alias _
    "WNetGetUserA" (ByVal lpName As String, _
    ByVal lpUserName As String, lpnLength As Long) As Long

Then, create a function with this code:

Public Function WinUserName() As String
Dim lUserNameLen As Long
Dim stTmp As String Dim lReturn As Long Do ' Set up the buffer stTmp = String$(lUserNameLen, vbNullChar) lReturn = WNetGetUser(vbNullString, stTmp, lUserNameLen) ' Continue looping until the call succeeds or the buffer ' can't fit any more data Loop Until lReturn <> ERRORMOREDATA If lReturn = ERR_SUCCESS ...

Get Access™ 2007 VBA Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.