如何在XMLHTTP onTimeOut时使用VBAcallback函数?

我试图从Web服务器获取XML数据到Excel,然后我写了一个sendRequest函数在Excel中调用

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

当networking服务器有问题时,无法连接或找不到,excel没有响应,太可怕了! 为了避免这种情况,我认为我们应该设定时间输出。 这些是我的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 )。 但是正如在我的testing中 , OnTimeOutMessagesendRequest()

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

感谢您的帮助!

线路;

XMLHTTP.OnTimeOut = OnTimeOutMessage

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

根据您的示例链接, JavaScript中的等效行正确地将一个Function对象分配给OnTimeOut以便后续调用 – VBA不支持此对象。

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

Tim是正确的,如果你有超时,那么每个请求将会“挂起”Excel / VBA,直到超时持续时间结束。 使用asynchronous将允许您多个请求没有长的请求延迟响应或进一步的请求。

status属性表示请求返回的HTTP状态码。 只需将下面的代码放在现有的代码中,以便进行较慢的同步检查,或将响应处理移至asynchronous的事件处理程序。

 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