Getting computer name using VBA

后端 未结 3 496
暗喜
暗喜 2020-12-13 08:40

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

相关标签:
3条回答
  • 2020-12-13 09:19
    Dim sHostName As String
    
    ' Get Host Name / Get Computer Name
    
    sHostName = Environ$("computername")
    
    0 讨论(0)
  • 2020-12-13 09:32

    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
    
    0 讨论(0)
  • 2020-12-13 09:37

    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
    
    0 讨论(0)
提交回复
热议问题