【发布时间】:2011-04-02 20:06:28
【问题描述】:
有没有办法在 VBA 中获取计算机的名称?
【问题讨论】:
标签: vba environment-variables computer-name
有没有办法在 VBA 中获取计算机的名称?
【问题讨论】:
标签: vba environment-variables computer-name
devhut 提供的一种读取环境变量的 shell 方法
Debug.Print CreateObject("WScript.Shell").ExpandEnvironmentStrings("%COMPUTERNAME%")
同源给出了一个API方法:
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
【讨论】:
看起来我来晚了,但这是一个常见的问题......
这可能是你想要的代码。
请注意,此代码位于公共领域,来自 Usenet、MSDN 和 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
你可能也需要这个:
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
【讨论】:
WScript.Network 而不是Environ()。注意:您可以在一行中使用ComputerName = CreateObject("WScript.Network").ComputerName
Environ() 的可变性似乎对于大多数初学者和中级开发人员来说是未知的,这让我很担心:你有参考 - 权威解释的链接 - 我可以添加到我的答案中吗?
With CreateObject("WScript.Network"),那么该对象将在End With 之后正确地被垃圾收集
Dim sHostName As String
' Get Host Name / Get Computer Name
sHostName = Environ$("computername")
【讨论】:
CreateObject("WScript.Network").ComputerName 回答这个问题:stackoverflow.com/a/10108951/1915920
你可以这样做:
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
【讨论】: