Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Question About Code That Grabs Logged On User Name

Status
Not open for further replies.

kc27

Technical User
Sep 10, 2008
171
0
0
US
I have an Excel form that uses the code below to get the logged on user's ID.

What is this line of the code doing? Is it subtracting a character where it reads "-1"? Is it removing a character?

Code:
Private Sub Workbook_Open()
    Dim lpBuff As String * 25
    ret = GetUserName(lpBuff, 25)
    logonUser = Left(lpBuff, InStr(lpBuff, Chr(0)) - 1)
    ThisWorkbook.Names("CurrUsername").RefersTo = "=" & logonUser
    ThisWorkbook.Names("CurrUserAlias").RefersTo = "=" & logonUser
 
It finds position of first Chr(0) in the string, after deducting 1 you get the length of substring before it (initial lpBuff has 25 such characters, GetUserName fills it with logon name).
GetUserName is API function, you can get the same result in VBA with:
[tt]logonUser = Environ("UserName")[/tt]

combo
 
Hi,

How/where is lpBuff assigned?

That being said, this statement...
Code:
logonUser = Left(lpBuff, InStr(lpBuff, Chr(0)) - 1)
... is 1) finding where Chr(0) appears in lpBuff, 2) subtracting 1 and then 3) returning that many characters from the left of lpBuff.

Skip,
[sub]
[glasses]Just traded in my OLD subtlety...
for a NUance![tongue][/sub]
 
Thanks for the answers. I was wondering if the code removes any leading zeros. It does not sound like it does.

This is where the name is derived

Code:
'Windows API
Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
 
For an identifier, which is what a UserID is, you wouldn’t want leading zeros removed.

Skip,
[sub]
[glasses]Just traded in my OLD subtlety...
for a NUance![tongue][/sub]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top