Share via

Difference between Environ function or API function to get the window session username

Anonymous
2014-12-10T09:17:37+00:00

Hello

I used previously this API function

Declare Function wu_GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Function GetUserName() As Variant

   Dim strUserName As String, lngLength As Long, lngResult As Long

   strUserName = String$(255, 0)

   lngLength = 255

   lngResult = wu_GetUserName(strUserName, lngLength)

   GetUserName = Left(strUserName, InStr(1, strUserName, Chr(0)) - 1)

End Function

Similarly, you could use : Environ("username")

Both function return the same string that needs to be the current user/window session logged on that pc.

Any comment ?

Regards

JY

Microsoft 365 and Office | Excel | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

6 answers

Sort by: Most helpful
  1. Anonymous
    2014-12-10T17:41:09+00:00

    Environ is a VB/VBA function - the other can be used with any language.

    Was this answer helpful?

    0 comments No comments
  2. Anonymous
    2014-12-10T15:33:35+00:00

    Hi Hans

    I suspected something like that  ...

    Maybe it is also historical, that the Environ function was only released later ?

    Regards

    JY

    Was this answer helpful?

    0 comments No comments
  3. Anonymous
    2014-12-10T15:29:52+00:00

    Hi Bernie

    For Application.UserName, I know that you could just use

    Application.UserName= "Mickey Mouse" before saving any file,  ( could be usefull at some time)

    Therefor, I use normally the API function

    Thank you

    Regards

    JY

    Was this answer helpful?

    0 comments No comments
  4. HansV 462.6K Reputation points
    2014-12-10T14:24:22+00:00

    Someone who is computer-savvy could change the username environment string, so Environ("username") is not 100% dependable. As far as I know, it's far more difficult (if possible at all) to change the result of the API function.

    Was this answer helpful?

    0 comments No comments
  5. Anonymous
    2014-12-10T14:23:37+00:00

    They return the same information, just through different mechanisms. Note that 

    Application.UserName

    may differ, since the user gets to set that in Excel options.

    Was this answer helpful?

    0 comments No comments