当XMLHTTP超时时如何回调VBA函数?

7

我正在尝试从Web服务器获取XML数据并将其导入Excel,然后我编写了一个sendRequest函数在Excel中调用。

=sendRequest("http://abb.com/index.php?id=111")

当 Web 服务器出现问题、无法连接或找不到时,Excel 不响应,这真是太糟糕了!为了避免这种情况,我认为我们应该设置 timeOut。以下是我的函数:

Function sendRequest(Url)
    'Call service
    Set XMLHTTP = CreateObject("Msxml2.ServerXMLHTTP.6.0")

    'Timeout values are in milli-seconds
    lResolve = 10 * 1000
    lConnect = 10 * 1000
    lSend = 10 * 1000
    lReceive = 15 * 1000 'waiting time to receive data from server
    XMLHTTP.setTimeOuts lResolve, lConnect, lSend, lReceive

    XMLHTTP.OnTimeOut = OnTimeOutMessage 'callback function

    XMLHTTP.Open "GET", Url, False

    On Error Resume Next
    XMLHTTP.Send
    On Error GoTo 0

    sendRequest = (XMLHTTP.responseText)
End Function

Private Function OnTimeOutMessage()
    'Application.Caller.Value = "Server error: request time-out"
    MsgBox ("Server error: request time-out")
End Function

通常情况下,当XMLHTTP超时时,事件OnTimeOutMessage将被执行(参考#1, #2)。但是在我的测试中,OnTimeOutMessage会在sendRequest()开始时立即执行。

如何在Msxml2.ServerXMLHTTP.6.0请求超时时使用回调函数?

感谢您的帮助!


1
可能的方法在这里:http://www.dailydoseofexcel.com/archives/2006/10/09/async-xmlhttp-calls/ - Tim Williams
@TimWilliams 谢谢!但我没有找到异步解决方案。我只想在xmlhttp超时时使用回调函数。我有一个小理由这样做,因为我的Web服务器很弱,如果我同时从“sendRequest - Excel”发送太多请求,它会显示“连接被拒绝”。 - Davuz
如果您不希望 Excel 在等待 XMLHttpRequest 的响应时锁定,则必须使用异步调用。 您可以使用该方法来处理其他事件。 - Tim Williams
2个回答

5

这一行代码:

XMLHTTP.OnTimeOut = OnTimeOutMessage

不是一个方法分配,它会立即执行OnTimeOutMessage()(并将其无用的返回值赋值给OnTimeOut)。

根据您提供的示例链接,在JavaScript中,等效的代码正确地为OnTimeOut分配了一个Function对象以便后续调用 - 但是,在VBA中不支持此操作。

相反,您可以捕获.send后引发的超时错误或使用早期绑定、WithEvents和内联事件处理程序。


1
哦,有这么多解决方案!你能清楚地提供信息吗?如何捕获.send后引发的超时错误?我搜索了“早期绑定”,但找到了更多的“晚期绑定”结果:(可以使用withEvents[如此][1]吗?什么是内联事件处理程序?非常感谢![1]http://www.cpearson.com/excel/Events.aspx - Davuz

3

如果你的请求存在超时,那么每个请求都会让Excel/VBA暂停,直到超时时间结束才会继续执行。使用异步方式可以让你发送多个请求,而不会因为一个长时间等待响应或者后续请求而延迟。

状态属性表示请求返回的HTTP状态码。只需要将以下代码放入现有代码中进行较慢的同步检查,或将响应处理移动到异步事件处理程序中即可。

XMLHTTP.Send

If XMLHTTP.Status = "200" Then
    '200      OK
    htmlString = XMLHTTP.ResponseText
Elseif XMLHTTP.Status = "408" Then
    '408      Request Timeout
    Call OnTimeOutMessage
else
    'All status return values
    'Number      Description
    '100      Continue
    '101      Switching protocols
    '200      OK
    '201      Created
    '202      Accepted
    '203      Non-Authoritative Information
    '204      No Content
    '205      Reset Content
    '206      Partial Content
    '300      Multiple Choices
    '301      Moved Permanently
    '302      Found
    '303      See Other
    '304      Not Modified
    '305      Use Proxy
    '307      Temporary Redirect
    '400      Bad Request
    '401      Unauthorized
    '402      Payment Required
    '403      Forbidden
    '404      Not Found
    '405      Method Not Allowed
    '406      Not Acceptable
    '407      Proxy Authentication Required
    '408      Request Timeout
    '409      Conflict
    '410      Gone
    '411      Length Required
    '412      Precondition Failed
    '413      Request Entity Too Large
    '414      Request-URI Too Long
    '415      Unsupported Media Type
    '416      Requested Range Not Suitable
    '417      Expectation Failed
    '500      Internal Server Error
    '501      Not Implemented
    '502      Bad Gateway
    '503      Service Unavailable
    '504      Gateway Timeout
    '505      HTTP Version Not Supported

End If

感谢@osknows!如何使用您的代码?当XMLHTTP.Send超时时,XMLHTTP.Status为空。 - Davuz
如果您想特别处理OnTimeOut事件,则设置一个类模块,类似于Tim提供的链接。如果.Status返回错误,则'htmlString = XMLHTTP.ResponseText'也会导致错误;如果您正确处理错误,则可以测试htmlString = vbnullstring并知道您有一个错误。顺便说一下,您提供的原始链接对我来说返回404状态。 - user688334
我已经尝试使用异步方法和setTimeouts,但我的函数在任何地方退出,我无法在代码中捕获错误408 - 请求超时。请问在http://www.dailydoseofexcel.com/archives/2006/10/09/async-xmlhttp-calls/的演示中应该把你的代码放在哪里? - Davuz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接