使用 VBA 获取计算机名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3551055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting computer name using VBA
提问by l--''''''---------''''''''''''
Is there a way to get the name of the computer in VBA?
有没有办法在VBA中获取计算机的名称?
回答by Tommy
Dim sHostName As String
' Get Host Name / Get Computer Name
sHostName = Environ$("computername")
回答by Sarfraz
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
回答by Nigel Heffernan
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.
请注意,此代码属于公共领域,来自 Usenet、MSDN 和Excellerando 博客。
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

