XMLHTTP 6. & api Internet Connection Check

keromero

Board Regular
Joined
Feb 20, 2025
Messages
55
Office Version
  1. 2016
I facilitate below code based on XMLHTTP 6. & api. in order to check whether internet is connected. IF internet is connected excel sheet will be loaded otherwise workbook will be closed (If there is else other opened workbooks) or application quit (It this workbook is the only one)

The code works fine If I disconnect ethernet connection or wifi connection. However If I switch off modem/router or disconnect Wan cable of modem / router randomly I receive false positives. Where do I go wrong?

Thanks




Function InternetTime(Optional GMTDifference As Integer) As Date

'-----------------------------------------------------------------------------------
'This function returns the Greenwich Mean Time retrieved from an internet server.
'You can use the optional argument GMTDifference in order to add (or subtract)
'an hour from the GMT time. For Example if you call the function as:
'=InternetTIme(2) it will return the (local) hour GMT + 2. Note that the
'GMTDifference variable is an integer number.

'Written by: Christos Samaras
'Date: 25/09/2013
'Last Updated: 10/01/2017
'e-mail: xristos.samaras@gmail.com
'site: Home - My Engineering World
'-------------------------------------------------------------------------------

'Declaring the necessary variables.
Dim request As Object
Dim ServerURL As String
Dim Results As String
Dim NetDate As String
Dim NetTime As Date
Dim LocalDate As Date
Dim LocalTime As Date

'Check if the time difference is within the accepted range.
If GMTDifference < -12 Or GMTDifference > 14 Then
Exit Function
End If

'The server address.
ServerURL = "Abu Dhabi, United Arab Emirates - current and accurate time"

'Build the XMLHTTP object and check if was created successfully.
On Error GoTo errorHandler
Set request = CreateObject("MSXML2.ServerXMLHTTP.6.0")
If Err.Number <> 0 Then
Exit Function
End If

On Error GoTo errorHandler

'Create the request.
request.Open "GET", ServerURL, False, "", ""

'Send the request to the internet server.
request.send

'Based on the status node result, proceed accordingly.
If request.readyState = 4 Then

'If the request succeed, the following line will return
'something like this: Mon, 30 Sep 2013 18:33:23 GMT.
Results = request.getResponseHeader("date")

'Use the Mid function to get something like: 30 Sep 2013 18:33:23.
Results = Mid(Results, 6, Len(Results) - 9)

'Use the Left and Right function to distinguish the date and time.
NetDate = Left(Results, Len(Results) - 9) '30 Sep 2013
NetTime = Right(Results, 8) '18:33:23

'Convert the date into a valid Excel date 30 Sep 2013 -> 30/9/2013.
'Required for countries that have some non-Latin characters at their alphabet (Greece, Russia, Serbia etc.).
LocalDate = ConvertDate(NetDate)

'Add the hour difference to the retrieved GMT time.
LocalTime = NetTime + GMTDifference / 24

'Return the local date and time.
InternetTime = LocalDate + LocalTime

Exit Function

errorHandler:
MsgBox "Error" & Str(Err.Number) & Chr(13) & _
"Validation failed!" & Chr(13) & _
"Please make sure you have a valid internet connection.", vbCritical, "Acolator Units"

If Workbooks.count = 1 Then
Application.DisplayAlerts = False
Application.Quit
ThisWorkbook.Save
Else
ThisWorkbook.Close 'SaveChanges:=True
End If

End If

'Release the XMLHTTP object.
Set request = Nothing

End Function

Function ConvertDate(strDate As String) As Date

'-------------------------------------------------------------------------
'This function converts the input date into a valid Excel date.
'For example the 30 Sep 2013 becomes 30/9/2013.
'Required for countries that have non-Latin characters at their alphabet.

'Written by: Christos Samaras
'Date: 25/09/2013
'e-mail: xristos.samaras@gmail.com
'site: Home - My Engineering World
'-------------------------------------------------------------------------

'Declaring the necessary variables.
Dim MyMonth As Integer

'Check the month and convert it to number.
Select Case UCase(Mid(strDate, 4, 3))
Case "JAN": MyMonth = 1
Case "FEB": MyMonth = 2
Case "MAR": MyMonth = 3
Case "APR": MyMonth = 4
Case "MAY": MyMonth = 5
Case "JUN": MyMonth = 6
Case "JUL": MyMonth = 7
Case "AUG": MyMonth = 8
Case "SEP": MyMonth = 9
Case "OCT": MyMonth = 10
Case "NOV": MyMonth = 11
Case "DEC": MyMonth = 12
End Select

'Rebuild the date.
ConvertDate = DateValue(Right(strDate, 4) & "/" & MyMonth & "/" & Left(strDate, 2))

End Function

Sub UpdateAll()

'Recalculate all the workbook in order to update the InternetTIme function results.
Application.CalculateFull

End Sub
 
Hi @keromero
What exactly do you mean by false positives ? And random ones? What is the request.status in such cases?
What is your operating system? Is the lack of internet connection detected by the system?

I could not replicate such behaviour, although to be honest I modified your code a bit - IMO some things you should do differently:
- take the error handling block out of the if block and put it at the end of the procedure
- do not use message boxes in functions
A few extra comments:
- use code tags when posting code here
- many reasons can raise an error in your code (e.g. server down, wrong server address, unreachable DNS) so I wouldn't really think of it as an "Internet Connection Check"
 
Upvote 0
Hi @keromero
What exactly do you mean by false positives ? And random ones? What is the request.status in such cases?
What is your operating system? Is the lack of internet connection detected by the system?

I could not replicate such behaviour, although to be honest I modified your code a bit - IMO some things you should do differently:
- take the error handling block out of the if block and put it at the end of the procedure
- do not use message boxes in functions
A few extra comments:
- use code tags when posting code here
- many reasons can raise an error in your code (e.g. server down, wrong server address, unreachable DNS) so I wouldn't really think of it as an "Internet Connection Check"

Hi Bobsan, please see answers / comments as follows:

What exactly do you mean by false positives



? And random ones? What is the request.status in such cases?
What is your operating system? Is the lack of internet connection detected by the system?
 
Upvote 0
Hi Bobsan, please see answers / comments as follows:

What exactly do you mean by false positives



? And random ones? What is the request.status in such cases?
What is your operating system? Is the lack of internet connection detected by the system?
Hi Bobsan, please see answers / comments as follows:

What exactly do you mean by false positives
- In case I disconnect the ethernet connection or unplug ethernet cable, "error handler" executes correctly; however If I switch off modem/router or disconnect wan connection to modem/router the "errorhandler" not responds correctly and the execution continuous to open file, according to above vode where we expect the application quit or workbook close

And random ones?
- This mean above "error handler" occasionally working fine other times not (If I switch off modem/router or disconnect wan connection to modem/router)

What is the request.status in such cases?
- Idea, in case there is "error" than error handler will quit workbook. Otherwise code gets "Date" from time server and compares to a date (which is such an expiration date) saved in workbook. If expiration date is earlier than Tİme server date, workbook closed and application quits.

What is your operating system? Is the lack of internet connection detected by the system?
- Windows 10 / 64 bit -ver. 2009-19045.5737
 
Upvote 0
What is the request.status in such cases?
I suggest you debug this a bit more in details.
Pause the sub execution in case of false positive and investigate the request object in more details
 
Upvote 0

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top