Get the Current Username

By | 2007-05-22

Get the username of the currently logged on user.

Option Explicit

Private Const UNKNOWN = "(Value Unknown Because System Call Failed)"
Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Public Function GetCurrentUserName() As String

  Dim l As Long
  Dim sUser As String

  sUser = Space$(255)
  l = GetUserName(sUser, 255)
  ' strip null terminator

  If l <> 0 Then
    GetCurrentUserName = Left(sUser, InStr(sUser, Chr(0)) - 1)
  Else
    Err.Raise Err.LastDllError, , "A system call returned an error code of " & Err.LastDllError
  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.