Search code examples
vbaexcel

Excel VBA - Check if connected to internet AND if its via Wifi or Ethernet


I need to alert users before running a macro which takes a lot longer if run on Wifi as opposed to the company LAN.


I have found the following code:

Checking for internet connection using VBA

The following code snippet uses API functions to check Internet connectivity and also the type of connection :

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

If you want to know just if it is connected or not you can use the following:

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

This tells me I have a LAN connection, but it does so whether I am on WIFI or connected to the LAN. I need to distinguish between them.

Does anyone know how I can do this please?

Cheers


Solution

  • Try this, It loops through each connection and gets the ID , AdapterType and ConnectionStatus. Just use the one you need.

    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
    

    Thanks to to @tom preston, a link to Win32_NetworkAdapter class.