我有一个看起来像这样的函数
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调用,然后一次返回所有数据?
答案 0 :(得分:1)
您可以在模块中使用全局变量来缓存和重复使用已下载的数据。
第一个易于理解的示例,使用简单的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
当然,所有这些代码都进入了模块。