使用VBA获取计算机名称

时间:2010-08-23 19:38:42

标签: vba environment-variables username computer-name

有没有办法在VBA中获取计算机的名称?

4 个答案:

答案 0 :(得分:57)

Dim sHostName As String

' Get Host Name / Get Computer Name

sHostName = Environ$("computername")

答案 1 :(得分:17)

你可以这样做:

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

答案 2 :(得分:8)

看起来我已经迟到了,但这是一个常见的问题...

这可能是您想要的代码。

请注意,此代码位于公共域,来自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

你可能也需要这个:

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

答案 3 :(得分:1)

用于读取环境变量的 shell 方法 devhut

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