How to get name of the computer in VBA?
Asked Answered
R

4

49

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

Record answered 23/8, 2010 at 19:38 Comment(0)
A
70
Dim sHostName As String

' Get Host Name / Get Computer Name

sHostName = Environ$("computername")
Anarchic answered 23/8, 2010 at 19:40 Comment(3)
Note that Environ variables must be handled with care because they are a security risk (#3366692)Crucial
@Crucial I disagree. That's not a security risk with the handling of environment variables, but rather code that is susceptible to SQL injection.Holmun
better (security, immutability) use the more robust CreateObject("WScript.Network").ComputerName from Nigel Heffernan's answer for this question: https://mcmap.net/q/350167/-how-to-get-name-of-the-computer-in-vbaAbott
D
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
Drogheda answered 23/8, 2010 at 19:40 Comment(1)
Looks like you found the same website that I did :)Anarchic
D
18

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
Dhammapada answered 11/4, 2012 at 15:20 Comment(4)
Question asked for the name of the computer, not the user (though that would be useful also).Judges
+1 for using WScript.Network instead of Environ(). Note: you can do it in one line with ComputerName = CreateObject("WScript.Network").ComputerNameBrine
Thanks 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?Dhammapada
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 WithSaturate
N
4

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
Namnama answered 3/1, 2021 at 10:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.