gpt4 book ai didi

excel - XMLHTTP onTimeOut 时如何使用 VBA 回调函数?

转载 作者:行者123 更新时间:2023-12-01 22:49:11 26 4
gpt4 key购买 nike

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

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

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

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)。但如 my test 所示, OnTimeOutMessagesendRequest()

的开头执行

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

感谢您的帮助!

最佳答案

线;

XMLHTTP.OnTimeOut = OnTimeOutMessage

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

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

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

关于excel - XMLHTTP onTimeOut 时如何使用 VBA 回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11407010/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com