47

Is there a way to get the name of the computer in VBA?

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062

4 Answers4

70
Dim sHostName As String

' Get Host Name / Get Computer Name

sHostName = Environ$("computername")
Tommy
  • 39,592
  • 10
  • 90
  • 121
  • 6
    Note that Environ variables must be handled with care because they are a security risk (http://stackoverflow.com/questions/3366192/using-nt-login-as-part-of-sql-query-run-via-vba-in-access-2007) – Fionnuala Aug 23 '10 at 21:19
  • 4
    @Fionnuala I disagree. That's not a security risk with the handling of environment variables, but rather code that is susceptible to SQL injection. – Josh Stodola Jan 27 '17 at 17:37
  • 3
    better (security, immutability) use the more robust **`CreateObject("WScript.Network").ComputerName`** from *Nigel Heffernan's* answer for this question: https://stackoverflow.com/a/10108951/1915920 – Andreas Covidiot Sep 10 '19 at 12:11
23

You can do like this:

Sub Get_Environmental_Variable()

Dim sHostName As String
Dim sUserName As String

' Get Host Name / Get Computer Name    
sHostName = Environ$("computername")

' Get Current User Name    
sUserName = Environ$("username")

End Sub
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
17

Looks like I'm late to the game, but this is a common question...

This is probably the code you want.

Please note that this code is in the public domain, from Usenet, MSDN, and the Excellerando blog.

Public Function ComputerName() As String
'' Returns the host name

'' Uses late-binding: bad for performance and stability, useful for 
'' code portability. The correct declaration is:

'   Dim objNetwork  As IWshRuntimeLibrary.WshNetwork
'   Set objNetwork = New IWshRuntimeLibrary.WshNetwork

    Dim objNetwork As Object
    Set objNetwork = CreateObject("WScript.Network")

    ComputerName = objNetwork.ComputerName
    
    Set objNetwork = Nothing

End Function

You'll probably need this, too:

Public Function UserName(Optional WithDomain As Boolean = False) As String
'' Returns the user's network name

'' Uses late-binding: bad for performance and stability, useful for
'' code portability. The correct declaration is:

'   Dim objNetwork  As IWshRuntimeLibrary.WshNetwork
'   Set objNetwork = New IWshRuntimeLibrary.WshNetwork


    Dim objNetwork As Object
    Set objNetwork = CreateObject("WScript.Network")

    If WithDomain Then
        UserName = objNetwork.UserDomain & "\" & objNetwork.UserName
    Else
        UserName = objNetwork.UserName
    End If
    
    Set objNetwork = Nothing

End Function
Nigel Heffernan
  • 4,636
  • 37
  • 41
  • Question asked for the name of the computer, not the user (though that would be useful also). – Rob I Aug 12 '13 at 13:12
  • 4
    +1 for using `WScript.Network` instead of `Environ()`. Note: you can do it in one line with `ComputerName = CreateObject("WScript.Network").ComputerName` – Andre Mar 10 '17 at 11:43
  • 1
    Thanks [Andre](https://stackoverflow.com/users/3820271/andre) - I often use the one-line format, but StackOverflow is for explanation as well as copy-and-code samples, so I try to lay out an explanatory answer. The mutability of `Environ()` seems to be unknown to most beginner and intermediate-level developers, and this worries me: do you have a reference - a link to an authoritative explanation - I can add to my answer? – Nigel Heffernan Oct 19 '17 at 15:20
  • 3
    Always create and destroy objects properly. If you don't want to declare you an use `With CreateObject("WScript.Network")` then the object will be garbage collected properly after the `End With` – HackSlash Apr 01 '20 at 20:45
3

A shell method to read the environmental variable for this courtesy of devhut

Debug.Print CreateObject("WScript.Shell").ExpandEnvironmentStrings("%COMPUTERNAME%")

Same source gives an API method:

Option Explicit

#If VBA7 And Win64 Then
    'x64 Declarations
    Declare PtrSafe Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#Else
    'x32 Declaration
    Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#End If

Public Sub test()

    Debug.Print ComputerName
    
End Sub

Public Function ComputerName() As String
    Dim sBuff                 As String * 255
    Dim lBuffLen              As Long
    Dim lResult               As Long
 
    lBuffLen = 255
    lResult = GetComputerName(sBuff, lBuffLen)
    If lBuffLen > 0 Then
        ComputerName = Left(sBuff, lBuffLen)
    End If
End Function
QHarr
  • 83,427
  • 12
  • 54
  • 101