Return server error from function as string?

Blue1971

New Member
Joined
May 19, 2020
Messages
15
Office Version
  1. 2016
Platform
  1. Windows
I have an Excel VBA function that takes a URL and returns a response.

VBA Code:
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)?
 

Excel Facts

Wildcard in VLOOKUP
Use =VLOOKUP("Apple*" to find apple, Apple, or applesauce
Try this:
VBA Code:
Public Function GetHTTP(ByVal url As String) As String

    On Error Resume Next
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", url, False: .send
        If Err.Number = 0 Then
            GetHTTP = StrConv(.responseBody, vbUnicode)
        Else
            GetHTTP = Err.Description
        End If
    End With
    On Error GoTo 0

End Function
 
Upvote 0
Try this:
VBA Code:
Public Function GetHTTP(ByVal url As String) As String

    On Error Resume Next
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", url, False: .send
        If Err.Number = 0 Then
            GetHTTP = StrConv(.responseBody, vbUnicode)
        Else
            GetHTTP = Err.Description
        End If
    End With
    On Error GoTo 0

End Function

Thanks. That works!
 
Upvote 0

Forum statistics

Threads
1,214,808
Messages
6,121,681
Members
449,048
Latest member
81jamesacct

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