Is there a way to get the name of the computer in VBA?
问题:
回答1:
Dim sHostName As String
' Get Host Name / Get Computer Name
sHostName = Environ$("computername")
回答2:
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
回答3:
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