Hello;
After many unsuccessful attempts to get the MS User Name (using different code snippets), the below code works when it's applied to a button on a form. However, what I would like to do is populate an unbound text box on the form, and, have it available when writing data to a table. I have been working on trying to get this working for way too many hours, and have tried so many iterations of code, placement, and hail-mary's I have lost count. If you have any suggestions I would surely appreciate it.
I have placed the Declare Function section in a Module, and placed the rest of the code as Private Sub, and also tried as Public Sub, (albeit I don't have a firm grasp on the functionality of the difference between Module and Class Module). I've tried the UserName = Environ("USERNAME")and couldn't get that to work either. But again, the below code returns the user name when the code is used as a Private Sub in the OnClick event of a button on the form where I want the user name to populate an unbound text box (not trying to file the user name from this form, just have it show to the user - I figure if I can get it to populate in the text box I can write it to a table in another form).
Using Access 2010 on a Win-7/64bit machine.
Thanks.
_______________________________________
' 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
Const NoError = 0 'The Function call was successful
Sub GetUserName()
' Buffer size for the return string.
Const lpnLength As Integer = 255
' Get return buffer space.
Dim status As Integer
' For getting user information.
Dim lpName, lpUserName As String
' 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)
Else
' An error occurred.
MsgBox "Unable to get the name."
End
End If
' Display the name of the person logged on to the machine.
MsgBox "The person logged on this machine is: " & lpUserName
End Sub