Reading a user's usrname with Visual Basic

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I am trying to validate a users username against an authorized database. I know there are MANY threads on how to do this with Visual Basic and in VB.Net. Here is what I have. I found this code using VBA that makes a call to advapi32.dll.
Tried it this morning in Excel and poof works like a champ.
Makes sure all variables are dimensioned in each subroutine.<br/>
Option Explicit
Access the GetUserNameA function in advapi32.dll and<br/>
call the function GetUserName.<br/>
Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _<br/>
(ByVal lpBuffer As String, nSize As Long) As Long
Main routine to Dimension variables, retrieve user name<br/>
and display answer.<br/>
Sub Get_User_Name()
Dimension variables<br/>
Dim lpBuff As String * 25<br/>
Dim ret As Long, UserName As String
Get the user name minus any trailing spaces found in the name.<br/>
ret = GetUserName(lpBuff, 25)<br/>
UserName = Left(lpBuff, InStr(lpBuff, Chr(0)) - 1)
Display the User Name<br/>
MsgBox UserName<br/>
Worksheets("Sheet1").Cells(20, 2).Value = UserName<br/>
End Sub
However after making the requisite changes for fixed length strings and taking out the Worksheets line of code and regenerating inside Visual studio, I get an entrypoint exceptioin when it calls the DLL. Why would this work inside VBA and have not
be able to call the same DLL from Visual Studio.
I have also used the My.User.Name construct and it returns an empty username variable.

View the full article
 
Back
Top