Excel VBA - 检查是否连接到互联网以及是否通过Wifi或以太网

时间:2017-01-26 10:12:43

标签: vba excel-vba excel

我需要在运行宏之前提醒用户,如果在Wifi上运行而不是公司LAN,则需要花费更长的时间。

我找到了以下代码:

Checking for internet connection using VBA

以下代码段使用API​​函数来检查Internet连接以及连接类型 :

Public Declare Function InternetGetConnectedState _
                         Lib "wininet.dll" (lpdwFlags As Long, _
                                            ByVal dwReserved As Long) As Boolean

Private Declare Function InternetGetConnectedStateEx Lib "wininet.dll" Alias "InternetGetConnectedStateExA" ( _
ByRef lpdwFlags As Long, _
ByVal lpszConnectionName As String, _
ByVal dwNameLen As Long, _
ByVal dwReserved As Long) As Long


'Local system uses a modem to connect to the Internet.
Private Const INTERNET_CONNECTION_MODEM As Long = &H1

'Local system uses a LAN to connect to the Internet.
Private Const INTERNET_CONNECTION_LAN As Long = &H2

'Local system uses a proxy server to connect to the Internet.
Private Const INTERNET_CONNECTION_PROXY As Long = &H4

The following API functions are used

Function IsConnected() As Boolean

    Dim Stat As Long

    IsConnected = (InternetGetConnectedState(Stat, 0&) <> 0)

    If IsConnected And INTERNET_CONNECTION_LAN Then
        MsgBox "Lan Connection"
    ElseIf IsConnected And INTERNET_CONNECTION_MODEM Then
        MsgBox "Modem Connection"
    ElseIf IsConnected And INTERNET_CONNECTION_PROXY Then
        MsgBox "Proxy"
    End If
End Function

如果您想知道它是否已连接,您可以使用以下内容:

CBool(InternetGetConnectedStateEx(0, vbNullString, 512, 0&))

这告诉我我有一个局域网连接,但无论我是在WIFI还是连接到局域网,它都会这样做。我需要区分它们。

有谁知道我怎么能这样做?

干杯

1 个答案:

答案 0 :(得分:3)

试试这个,它遍历每个连接并获得IDAdapterTypeConnectionStatus。只需使用你需要的那个。

Dim oObject
Dim adapter
Dim item

Set oObject = GetObject("WINMGMTS:\\.\ROOT\cimv2")

Set adapter = oObject.InstancesOf("Win32_NetworkAdapter")

    For Each item In adapter

        If item.NetconnectionID <> "null" Then
         Debug.Print item.NetconnectionID
         Debug.Print item.AdapterType
         Debug.Print item.NetConnectionStatus
     End If
    Next

感谢@tom preston,指向Win32_NetworkAdapter class的链接。