Monday, October 31, 2011

MSAccess: GetNetUser()

If you use "CurrentUser()" you will as often as not get "Admin", which is the default Access user.

To get the user's windows authentication login name, place the following code at the top of a standard module:


Private Declare Function WNetGetUserA Lib "mpr.dll" _
(ByVal lpszLocalName As String, ByVal lpszUserName As String, lpcchBuffer As Long) As Long

Public Function GetNetUser() As String
   Dim lpUserName As String, lpnLength As Long, lResult As Long
   'Create a buffer
   lpUserName = String(256, Chr$(0))
   'Get the network user
   lResult = WNetGetUserA(vbNullString, lpUserName, 256)
   If lResult = 0 Then
      GetNetUser = Left$(lpUserName, InStr(1, lpUserName, Chr$(0)) - 1)
   Else
      GetNetUser = "-unknown-"
   End If
End Function

It can be used in a query as GetNetUser() and in the control source of a text box on a form or report as =GetNetUser()

No comments:

Post a Comment