excel - 是否可以在 VBA 中对函数调用进行分组?

标签 excel vba function

我有一个看起来像这样的函数:

Public Function GetData(DataType As String) As String

    Dim Client As New WebClient
    Client.BaseUrl = "http://url/to/get/data"

    Dim Response As New WebResponse
    Set Response = Client.GetJson(DataType)

    GetInstruments = Response.Data("data")

End Function

它是一个简单的 HTTP GET,它根据参数返回一个值。

我的问题是我试图在 Excel 中一次为许多不同的单元格执行此函数(即 =GetData(A$1) ),这会导致数百个非常慢的 HTTP 调用。

有没有一种方法可以在 VBA 中拦截函数调用,这样我就可以进行一次快速的 HTTP 调用,然后一次返回所有数据?

最佳答案

您可以在模块中使用全局变量来缓存和重用已下载的数据。

第一个使用简单 Collection 的易于理解的示例:

Private someCollection As Collection

Public Function GetData() As Integer
    ' Make sure that data is already read/created
    If someCollection Is Nothing Then
        ' If we didn't get any data, then get it
        Set someCollection = New Collection
        someCollection.Add (1)
    End If
    ' Get data :)
    GetData = someCollection(1)
End Function

现在,将此逻辑应用于您的问题,您可以这样做:
Private Response As WebResponse

Public Function GetData(DataType As String) As String
    ' You can alter check to see if URL has changed.
    ' In order to do that just store URL in some global variable
    If Response Is Nothing Then
        Dim Client As New WebClient
        Client.BaseUrl = "http://url/to/get/data"
        Set Response = Client.GetJson(DataType)
    End If
    GetInstruments = Response.Data("data")
End Function

当然,所有这些代码都进入了模块。

关于excel - 是否可以在 VBA 中对函数调用进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53103184/

相关文章:

excel - 如何在 Excel 中使用范围变量名称

vba - 数据表新行中字段的默认值

oracle - 使用 FUNCTION 而不是 CREATE FUNCTION oracle pl/sql

excel - 数据更改时刷新excel电子表格中的所有数据透视表

python - 如何避免在 xlsxwriter (Python) 中覆盖单元格样式格式?

excel - 如何使用 Outlook VBA 获取工作表对象?

excel - 当数据透视表的选择更改时如何自动运行宏

excel - 如何在 VBA 中调暗和设置变量工作簿名称?

c - 函数头/声明

python - 有什么方法可以选择函数是否使用默认参数?