This article was previously published under Q161394
This article has been archived. It is offered "as is" and will no longer be updated.
The "More Information" section of this article contains sample MicrosoftVisual Basic for Applications code that calls WNetGetUser (a Windows APIfunction in the file Mpr.dll) to retrieve the user name used to establish anetwork connection.
Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs. If you have limited programming experience, you may want to contact a Microsoft Certified Partner or Microsoft Advisory Services. For more information, visit these Microsoft Web sites:
' 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
For more information about getting help with Visual Basic for Applications,please see the following article in the Microsoft Knowledge Base:
ARTICLE-ID: 163435 VBA: Programming Resources for Visual Basic for Applications