Get the Username of the Logged On User

By | 2019-08-22

This function will allow you to easily get the username of the currently logged on user.

Just pop it in to a module, and you’re good to go.

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

Public Function UserName() As String
   Dim cn As String
   Dim ls As Long
   Dim res As Long

   cn = String(1024, 0)
   ls = 1024
   res = GetUserName(cn, ls)
   If res <> 0 Then
      UserName = Mid(cn, 1, InStr(cn, Chr(0)) - 1)
   Else
      UserName = ""
   End If
End Function

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.