如何在Excel VBA中获取当前网络的名称?

时间:2013-01-18 16:10:44

标签: vba excel-vba excel

说我已连接到test.server.com以进行互联网访问。有没有办法让VBA返回该字符串?

根据您的要求进行扩展(抱歉,网络是我所知甚少的):

以下内容涉及Windows 7企业版:如果您要导航到“控制面板”中的“网络和共享中心”,这将是“域网络”的名称。或者,单击任务栏中的网络图标将显示此网络名称下方的“Internet访问”。

2 个答案:

答案 0 :(得分:8)

您可以从Windows基础API获取带有GetComputerNameEx的DNS主机和/或域名:

Option Explicit

Enum COMPUTER_NAME_FORMAT
    ComputerNameNetBIOS
    ComputerNameDnsHostname
    ComputerNameDnsDomain
    ComputerNameDnsFullyQualified
    ComputerNamePhysicalNetBIOS
    ComputerNamePhysicalDnsHostname
    ComputerNamePhysicalDnsDomain
    ComputerNamePhysicalDnsFullyQualified
End Enum

Declare Function GetComputerNameEx Lib "kernel32" Alias "GetComputerNameExA" ( _
    ByVal NameType As COMPUTER_NAME_FORMAT, _
    ByVal lpBuffer As String, _
    ByRef lpnSize As Long) As Long

Sub test()
    Dim buffer As String
    Dim size As Long
    size = 255
    buffer = Space(size)
    GetComputerNameEx ComputerNameDnsFullyQualified, buffer, size
    Debug.Print Left$(buffer, size)
End Sub

答案 1 :(得分:0)

使用用户A. Webb的回复,我使用以下内容工作,它将整个计算机名称和网络拉下来然后将其削减。我确信有更漂亮的方法,但它确实有效。

Option Explicit

Enum COMPUTER_NAME_FORMAT
    ComputerNameNetBIOS
    ComputerNameDnsHostname
    ComputerNameDnsDomain
    ComputerNameDnsFullyQualified
    ComputerNamePhysicalNetBIOS
    ComputerNamePhysicalDnsHostname
    ComputerNamePhysicalDnsDomain
    ComputerNamePhysicalDnsFullyQualified
End Enum

Declare Function GetComputerNameEx Lib "kernel32" Alias "GetComputerNameExA" ( _
ByVal NameType As COMPUTER_NAME_FORMAT, _
ByVal lpBuffer As String, _
ByRef lpnSize As Long) As Long

Sub test()

Dim buffer As String
Dim size As Long
Dim network_and_computer As String
Dim network_name As String

size = 255
buffer = Space(size)
GetComputerNameEx ComputerNameDnsFullyQualified, buffer, size
network_and_computer = Left$(buffer, size)

MsgBox network_and_computer

network_name = Right(network_and_computer, Len(network_and_computer) - InStr(1, network_and_computer, ".", vbTextCompare))

MsgBox network_name

End Sub