access vba code to get logged on user name
Posted on 2012-09-02
I have a button on the form that calls a on click sub that calls this function
if someone has a better way of getting the information straight from the sub I would appreciate it or tell me what is wrong with this function.
i have the following code in module1
for the line:status = WNetGetUser(lpName, lpUserName, lpnLength)
it tells me invalid outside of procedure
Option Compare Database
Const NoError = 0 'The Function call was successful
Const lpnLength As Integer = 255
Dim lpName, lpUserName As String
' Declare for call to mpr.dll.
Declare Function WNetGetUser Lib "mpr.dll" _
Alias "WNetGetUserA" (ByVal lpName As String, _
ByVal lpUserName As String, lpnLength As Long) As Long
' Buffer size for the return string.
' Get return buffer space.
Dim status As Integer
' For getting user information.
' Assign the buffer size constant to lpUserName.
' lpUserName = Space$(lpnLength + 1)
' Get the log-on name of the person using product.
status = WNetGetUser(lpName, lpUserName, lpnLength)
' See whether error occurred.
If status = NoError Then
' This line removes the null character. Strings in C are null-
' terminated. Strings in Visual Basic are not null-terminated.
' The null character must be removed from the C strings to be used
' cleanly in Visual Basic.
lpUserName = Left$(lpUserName, InStr(lpUserName, Chr(0)) - 1)
' An error occurred.
MsgBox "Unable to get the name."
' Display the name of the person logged on to the machine.
MsgBox "The person logged on this machine is: " & lpUserName