XMLHTTP onTimeOut 时如何使用 VBA 回调函数? [英] How to VBA callback function when XMLHTTP onTimeOut?

查看:37
本文介绍了XMLHTTP onTimeOut 时如何使用 VBA 回调函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从网络服务器获取 xml 数据到 excel,然后我编写了一个 sendRequest 函数来调用 excel

I'm trying get xml data from webserver to excel, then I wrote a sendRequest function to call in excel

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

当网络服务器出现问题,无法连接或找不到时,excel没有响应,太可怕了!为了避免它,我认为我们应该设置超时.这些是我的功能:

When web-server having trouble, cannot connect or cannot find, excel is not responding, it was horrible! To avoid it, i think we should set timeOut. These are my function:

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()

Normally, when XMLHTTP's timeout occurs, event OnTimeOutMessage will be executed (reference #1, #2). But as in my test, OnTimeOutMessage is executed right at the beginning of sendRequest()

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

How to use callback function when Msxml2.ServerXMLHTTP.6.0 request is time-out?

感谢您的帮助!

推荐答案

行;

XMLHTTP.OnTimeOut = OnTimeOutMessage

不是方法赋值;而是立即执行 OnTimeOutMessage()(并将其无用的返回值分配给 OnTimeOut).

Is not a method assignment; rather it immediately executes OnTimeOutMessage() (and assigns its useless return value to OnTimeOut).

JavaScript 中的等效行根据您的示例链接正确地将 Function 对象分配给 OnTimeOut 以供后续调用 - 这不受支持VBA.

The equivalent line in JavaScript as per your example link correctly assigns a Function object to OnTimeOut for subsequent invokation - this is not supported by VBA.

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

Instead, you could trap the timeout error raised after .send or use early binding, WithEvents, & inline event handlers.

这篇关于XMLHTTP onTimeOut 时如何使用 VBA 回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆