• Get Windows user name? (VBA/Excel 2000 sr-1)

    Home » Forums » AskWoody support » Productivity software by function » Visual Basic for Applications » Get Windows user name? (VBA/Excel 2000 sr-1)

    Author
    Topic
    #422599

    Is it possible to get the current Windows user name? I.e., if I log in to my machine as “Cristina”, then how to get back “Cristina”?

    Please be aware, question coming from a self-taught VBA programmer with limited knowledge of the wider Windows world … so if the answer (as I suspect) leads off into arcane topics like API functions or the Windows registry, please type slowly and use small words?

    Thanks!

    Viewing 1 reply thread
    Author
    Replies
    • #964333

      Copy/paste the following declaration to the top of a module, that is below Option Explicit (if you have that), but above all Subs and Functions:

      Private Declare Function GetUserName Lib “advapi32.dll” _
      Alias “GetUserNameA” (ByVal lpBuffer As String, nSize As Long) As Long

      Copy/paste the following function somewhere below it:

      Public Function WindowsUser() As String
      Dim strUsername As String
      strUsername = String(100, vbNullChar)
      GetUserName strUsername, 100
      WindowsUser = Left$(strUsername, InStr(strUsername, vbNullChar) – 1)
      End Function

      You can use this function to retrieve the Windows username, for example:

      Sub Test()
      MsgBox “Hello there, ” & WindowsUser
      End Sub

      • #964465

        Beautiful. That’s exactly what I need — thank you very much!

    • #964497

      A slightly simpler way is to use the VBA Environ function:

      MsgBox Environ("USERNAME")
      
      • #964505

        blush

      • #964527

        Provided that it is set, which it usually is in a Windows Server environment. Another obvious method with a Microsoft Application (the OP specified Excel) is:

        strUsername = Application.UserName

        doh laugh

        • #964541

          Application.Username doesn’t give the Windows Username of the logged in user, it gives the value of Tools > Options > User Information

          StuartR

          • #964546

            I’m out of my depth in the Server environment, but in my company I can’t log on to SuzyQ’s computer as JohnBF without having a new JohnBF profile created (or using an existing one if I have previously logged on), and in that case the Application.Username reflects the current user profile. (It had better, or the opportunities for sabotage are limitless. evilgrin)

            Outside that Server environment you are correct, when I use the Bride’s home PC, all my work product shows the Application.Username as “BrideofJohnBF”. grin

    Viewing 1 reply thread
    Reply To: Get Windows user name? (VBA/Excel 2000 sr-1)

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: