我正在尝试从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
请求超时时使用回调函数?
感谢您的帮助!