1

I have an Excel VBA function that takes a URL and returns a response (source: getHTTP with VBA?).

response = GetHTTP(.ListColumns(colNameURL).DataBodyRange(n).Value)

...

Public Function GetHTTP(ByVal url As String) As String

  With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", url, False: .Send
    GetHTTP = StrConv(.responseBody, vbUnicode)
  End With

End Function

The function works as expected.


However, if there is a problem with the URL (like the server being down), then the VBA editor pops up an error dialog.

Run-time error '-2147467259 (80004005)': Uspecified error

Instead of popping up a dialog, I would like the function to return the error message as a string.

Is there a way to return the server error as a string (without doing the HTTP call more than once)?


What I've tried:

I can get the function to return a pre-defined error message (from a constant).

Public Const InvalidURL = "Problem with URL or Server"


Public Function GetHTTP(ByVal url As String) As String

On Error GoTo ConnectionError:

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", url, False: .Send
        GetHTTP = VBA.StrConv(.responseBody, vbUnicode)
    End With

On Error GoTo 0

Exit Function

ConnectionError:
GetHTTP = InvalidURL

End Function

But that's not quite what I'm looking for. I want to return the true runtime error message (example: the error from the server).

1
  • 1
    You need to wrap an error handler around the Open() call Commented Jun 25, 2020 at 22:43

1 Answer 1

1

It was pretty simple:

GetHTTP = "Problem with URL or server: " & Err.Number & " " & Err.Description

Here's the full function:

Public Function GetHTTP(ByVal url As String) As String

On Error GoTo ConnectionError:

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", url, False: .Send
        GetHTTP = VBA.StrConv(.responseBody, vbUnicode)
    End With

On Error GoTo 0

Exit Function

ConnectionError:
GetHTTP = "Problem with URL or server: " & Err.Number & " " & Err.Description

End Function
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.