Home » excel » excel – Catching Timeout on VBA WinHttpRequest

excel – Catching Timeout on VBA WinHttpRequest

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to set Timeout values and catch this event if it happens using VBA and Excel. So far I tried with XMLHTTP60 and WinHttpRequest:

    Set XMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    With XMLHTTP
        .setTimeouts 11, 11, 11, 11 'Values for testing to get a timeout
        '.setTimeouts TIMEOUT_LRESOLVE, TIMEOUT_LCONNECT, TIMEOUT_LSEND, TIMEOUT_LRECEIVE
        .Open "GET", currenturl, False
        .send
        '.waitForResponse 1 'testing
        If .responseText Like "*PATH_NOT_FOUND*" Or .responseText Like "*OUTSIDE_BOUNDS*" Then
            noroutefound = True
            GoTo skiploop
        End If
        str = Split(.responseText, "{""startTime"":")
        complstr = .responseText
    End With

However, I am unable to catch an Error caused by a Timeout, or a Timeout itself.

How can I catch a Timeout?

How to&Answers:

Add error handling of On Error GoTo errHand before expected error and in the errHand: make sure you have

'Code
On Error GoTo errHand:
'Code producing error
Exit Sub
errHand

If err.Number <> 0 Then
     Debug.Print err.Message
End If
Exit Sub

If you have the error number of interest you can use select case err.Number to handle your specific error in a tailored way like for example:

errHand:

Select Case Err.Number
    Case -2147012894 'Code for Timeout
        Msgbox "Timeout"
    Case -2147012891 'Code for Invalid URL
        Msgbox "Invalid URL"
    Case Else 'Add more Errorcodes here if wanted
        MsgBox "Errornumber: " & Err.Number & vbnewline & "Errordescription: " & Error(Err.Number)
End select