Dav*_*vuz 8 excel vba msxml timeout callback
我正在尝试从webserver获取xml数据到excel,然后我写了一个sendRequest
函数来调用excel
=sendRequest("http://abb.com/index.php?id=111")
当网络服务器出现问题,无法连接或无法找到时,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
Run Code Online (Sandbox Code Playgroud)
通常,当XMLHTTP
超时发生时,OnTimeOutMessage
将执行事件(参考#1,#2).但正如在我的测试中,OnTimeOutMessage
在开始时执行sendRequest()
当Msxml2.ServerXMLHTTP.6.0请求超时时,如何使用回调函数?
谢谢您帮忙!
这条线;
XMLHTTP.OnTimeOut = OnTimeOutMessage
不是方法分配; 而是立即执行OnTimeOutMessage()
(并将其无用的返回值分配给OnTimeOut
).
根据您的示例链接,JavaScript中的等效行正确Function
地OnTimeOut
为后续调用指定了一个对象- VBA不支持此操作.
相反,您可以捕获之后引发的超时错误.send
或使用早期绑定WithEvents
和内联事件处理程序.