ProfessionalExcel.com In the office, Excel is a way of life… not just a tool

30Mar/124

Use VBA to test the internet connection

In some of my applications I utilise the IE web browser control to display reports, some of which request internet content (e.g. Google Chart API and Google Maps API).

The trouble is, you can't always guarantee that the users PC has an internet connection. So, what's the best approach to the problem? Well, check the internet connection using the handy bit if VBA code below!

Private Declare Function InternetGetConnectedStateEx Lib "wininet.dll" (ByRef lpdwFlags As Long, ByVal lpszConnectionName As String, ByVal dwNameLen As Integer, ByVal dwReserved As Long) As Long
 
'Testing for internet connection
Public Function IsInternetConnected() As Boolean
 
    IsInternetConnected = InternetGetConnectedStateEx(0, "", 254, 0)
 
End Function
Filed under: Userforms, VBA Leave a comment
Comments (4) Trackbacks (1)
  1. Thanks for this, I am using (a variant of) it for exactly the target problem. Much appreciated. On the code, I also don’t see the point in defining unused variables (maybe I’m missing something), nor using an intermediate boolean only to immediately pass into the function result. I think this does the exact same thing, am I missing something?

    Private Declare Function InternetGetConnectedStateEx Lib “wininet.dll” (ByRef lpdwFlags As Long, ByVal lpszConnectionName As String, ByVal dwNameLen As Integer, ByVal dwReserved As Long) As Long

    ‘Testing for internet connection
    Public Function Connected() As Boolean
    Connected = InternetGetConnectedStateEx(0, “”, 254, 0)
    End Function

  2. I use a similar function in one of my addins that must connect in order to retrieve results. I believe you can shorten your function a bit by using this as the last line:

    IsInternetConnect = (lngReturnStatus = 1)

    Also, there is no need to set the function value to False at the start of the function, because False is the default value for Boolean type.


Leave a comment