VBA:在Excel中创build会话持久对象(散列)

在VBA函数(UDF)中可以创build一个具有全局范围的对象吗? 即超越function的运行时间坚持? 我想把它粘在一个散列中,并且可以传递给其他函数。 我知道你可以在c#/ c ++ dll中做到这一点。

动机是一个沉重的处理,我不想重复数百个函数调用:我想caching结果,所以我只需要做一次。 假设我有一个在单元格A1中构build结果对象的UDF:

=CreateResultsObject(arg1, arg2, arg3...) 

该函数执行繁重的工作,并返回一个唯一的IDstring(存储在持久散列中的对象的键)。 单元格A1现在包含这个string值,然后我可以传递给其他函数:然后他们可以使用密钥访问散列中的caching对象。

这可能吗? 如果这样怎么样?

你在模块中声明的variables是持久的。

这个模块中的代码可能会进入你想要的方向:

 Option Explicit Dim col As New Collection Public Function GetValue(ByVal strName As String) As String GetValue = col.Item(strName) End Function Public Sub SetValue(ByVal strName As String, ByVal strValue As String) col.Add strValue, strName End Sub 

注意:

对于重复或缺less名字的代码将失败。 相应地,可以通过修改函数签名来传递任何types的对象而不是string值。

附录:

具有更多智能的相同代码 – 对于集合中的现有密钥,值将被replace而不是失败。

 Option Explicit Dim col As New Collection Public Function GetValue(ByVal strName As String) As String GetValue = col.Item(strName) End Function Public Sub SetValue(ByVal strName As String, ByVal strValue As String) If HasValue(strName) Then col.Remove (strName) End If col.Add strValue, strName End Sub Private Function HasValue(ByVal strName As String) As Boolean Dim val As Variant Dim bRes As Boolean bRes = True On Error Resume Next val = col.Item(strName) If Err.Number <> 0 Then bRes = False Err.Clear End If On Error GoTo 0 HasValue = bRes End Function 

在模块中使用全局variables怎么样?

像这样的东西:

 Option Explicit Dim sHash As String Function CreateResultsObject() 'very long code sHash = "MyTest" CreateResultsObject = "ok" End Function Function displayresultsobject() displayresultsobject = sHash End Function 

请注意,只有当您在工作表中调用CreateResultsObject()并且每次要求重新计算时,您的哈希都将被重新计算。