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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get User Name & Computer Name

Windows API

Get User Name & Computer Name

by  dsi  Posted    (Edited  )
Code:
Option Explicit

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

Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Public Sub Main()
    Dim sUser As String
    Dim sComputer As String
    Dim lpBuff As String * 1024

    'Get the Login User Name
    GetUserName lpBuff, Len(lpBuff)
    sUser = Left$(lpBuff, (InStr(1, lpBuff, vbNullChar)) - 1)
    lpBuff = ""
    
    'Get the Computer Name
    GetComputerName lpBuff, Len(lpBuff)
    sComputer = Left$(lpBuff, (InStr(1, lpBuff, vbNullChar)) - 1)
    lpBuff = ""

    MsgBox "Login User: " & sUser & vbCrLf & _
           "Computer Name: " & sComputer
    
    End
End Sub
Most Windows versions use environment variables as well.
Code:
sUser = VBA.Environ("USERNAME")

  and thanks to Kryzsoccer
sComputer = VBA.Environ("COMPUTERNAME")
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top