如何VBA发送Async XMLHTTP请求?

为了从Excel中的web服务获取数据,我创build了一个excel插件提供函数来获取它; 用户只需input单元格: =sendRequest("http://webservice.com")

我有两个excel文件,以两种方法来简化sending request :1. 同步和2. asynchronous

sync方法中,该function可以发送请求并正常获取数据。 但是,如果我们有100个,200个这样的单元格 ,就会花费Excel等待大量的时间; 这也使得Exel 不会重新调整

我目前的解决scheme是使用如下代码的 async方法

 Public Function sendAsyncRequest(URL) 'other statement ' Get some stuff asynchronously. xmlHttpRequest.Open "GET", URL, True xmlHttpRequest.send sendAsyncRequest = xmlHttpRequest.responseText End Function 

但单元格的值总是为0而不是repsone文本。

我必须使用我的处理程序类将其绑定到xmlHttpRequest object OnReadyStateChange以将响应文本设置为单元格。 但是,它也清除了单元格的公式。

所以我的问题是如何更改单元格的显示文本而不更改其公式?

我也欢迎另一种解决scheme发送请求并获取async方法下的返回值。

正如这里所说的解决scheme的缺点,获得函数的asynchronous返回值的方法是1)将request's url => returned value caching到集合/ dicitonary中,然后2) 刷新公式

这是我的解决scheme文件为您的问题; 实际上它是从你的asynchronoustesting文件更新的。

根据这种情况 ,您可以通过使用Range(yourCellAddress).NumberFormat =“0; 0; 0;”“Value to display”“”来change the display text of cell without changing its formula

所以对于你的问题,解决scheme是

  1. 在您的sendAsyncRequest函数中,将返回行replace为

    sendAsyncRequest = "anything other than numbers"

  2. 在您的ReadyStateChangeHandler子目录中,replace

    Application.Range(cellAddress).Value = XMLHttpReq.responseText 'return responseText to cell

通过

 cellDisplayText = XMLHttpReq.responseText Range(cellAddress).NumberFormat = "0;0;0;""" & cellDisplayText & """"