gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:10:08 28 4
gpt4 key购买 nike

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

<小时/>

我找到了以下代码:

Checking for internet connection using VBA

以下代码片段使用 API 函数来检查互联网连接以及连接类型:

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&))
<小时/>

这告诉我我有一个 LAN 连接,但无论我是在 WIFI 还是连接到 LAN 上,它都是如此。我需要区分它们。

有人知道我该怎么做吗?

干杯

最佳答案

试试这个,它循环遍历每个连接并获取 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的链接.

关于vba - Excel VBA - 检查是否连接到互联网以及是否通过 Wifi 或以太网,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41871138/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com