【问题标题】:How to VBA sends an Async XMLHTTP request?VBA 如何发送异步 XMLHTTPrequest?
【发布时间】:2012-07-11 00:19:21
【问题描述】:

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

我有 2 个 excel 文件以两种方法演示 sending request:1.synchronous 和 2.asynchronous

sync方法中,函数可以正常发送请求和获取数据。但是,如果我们有 100、200 个单元格调用它,Excel 将花费大量时间等待;这也使 Exel 不响应

我目前的解决方案是使用async 方法作为below code

Public Function sendAsyncRequest(URL)
    'other statement

    ' Get some stuff asynchronously.
    xmlHttpRequest.Open "GET", URL, True
    xmlHttpRequest.send
    sendAsyncRequest = xmlHttpRequest.responseText
End Function

但单元格的值始终为零 0 而不是响应文本。

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

所以我的问题是如何在不改变公式的情况下改变单元格的显示文本?

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

【问题讨论】:

  • 我的回答有一个严重的缺点,绝对不应该被接受。请取消选中它。

标签: excel vba asynchronous xmlhttprequest


【解决方案1】:

正如here 所述解决方案的缺点,获取函数异步返回值的正确方法是 1) 缓存 你的 request's url => returned value 到集合/字典,然后2) 刷新你的公式

【讨论】:

    【解决方案2】:

    这是我的solution file 供您提问;实际上它是从您的async test file 更新的。

    基于this discusion,您可以change the display text of cell without changing its formula 使用 Range(yourCellAddress).NumberFormat = "0;0;0;""要显示的值"""

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

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

      sendAsyncRequest = "anything other than numbers"

    2. 在您的 ReadyStateChangeHandler 子中,替换

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

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

    【讨论】:

    • 我也在这里重构了解决方案以获得更好的代码dl.dropbox.com/u/6194904/2012/…
    • 这个解决方案的一个缺点是我们看到的displayed text 值实际上不是单元格值;单元格值是“除数字以外的任何内容”。因此,如果单元格 A1 的 displayed value 为 122,并且我们在单元格 A2 的公式中使用它,例如 =A1+1,则该值不是 123,但结果为错误(由于将字符串添加到数字)
    猜你喜欢
    • 2017-06-18
    • 2017-09-10
    • 2015-12-01
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    相关资源
    最近更新 更多