VBA – Check for Active Internet Connection – Network Status

VBA Check if Computer is Connected to Network

Is your Excel or other Ms office application is fetching data from Internet?

Do You also wish to check if the computer is having an active network connection? – before fetching data from web.

Then this code will help You.

We are going to use the Windows API function ‘InternetGetConnectedState’. The official documentation of this function can be found in this link.

Lets get to the actual code.

VBA Code – Check for active Internet Connection

The above mentioned WINAPI function not only detects Network connection, it also determines what is the type of connection available – LAN, Proxy or Modem etc.,

Now, copy paste this code to a new module in your Excel VBA project.

Press F5 by switching the LAN ON & OFF to check if the status returned is good enough for your needs.

'Windows API Function
'To check if Computer is connected to Internet
Private Declare Function InternetGetConnectedState Lib "wininet.dll" ( _
    ByRef lpdwFlags As Long, _
    ByVal dwReserved As Long) _
    As Boolean

'Connection Type (LAN, MODEM, PROXY)
Const INTERNET_CONNECTION_LAN = &H2
Const INTERNET_CONNECTION_MODEM = &H1
Const INTERNET_CONNECTION_PROXY = &H4

'VBA Code To check if Internet is ON/OFF
Sub Check_If_Internet_Is_Connected()
    Dim lConnectionFlag As Long
    
    If InternetGetConnectedState(lConnectionFlag, 0) = True Then
        'Computer is Connected to Network
        
        'Now Find Type of Connection
        'LAN - Connection ON
        If lConnectionFlag And INTERNET_CONNECTION_LAN Then
             retMsg = "Connected to LAN"
        
        'MODEM - Connection ON
        ElseIf lConnectionFlag And INTERNET_CONNECTION_MODEM Then
            retMsg = "Connected using MODEM"
            
        'PROXY - Connection ON
        ElseIf lConnectionFlag And INTERNET_CONNECTION_PROXY Then
            'Proxy connection.
             retMsg = "Connection thru Proxy"
        End If
    Else
    
        'LAN/Internet/Network is OFF
         retMsg = "Computer Not Connected to Network/Internet - Check LAN Connection"
    End If
    
    'Display Status Message
    MsgBox retMsg

End Sub

If this code is being used in a 64 bit machine, refer this document on how to change it accordingly.

There is not much of code changes here. You just have to change the declaration of the Windows API function at the first line of the code.

Leave a Reply