VBA:在Excel中创建会话持久对象(哈希)

Ric*_*d H 1 excel hash session vba persistence

是否可以在VBA函数(UDF)中创建具有全局范围的对象?即坚持超出功能的运行时间?我想把它放在一个带有唯一键的哈希中,我可以传递给其他函数.我知道你可以在c#/ c ++ dll中做到这一点.

动机是一个繁重的处理过程,我不想在数百个函数调用中重复:我想缓存结果,所以我只需要做一次.例如,让我们假设我有一个UDF,它在Cell A1中构建结果对象:

=CreateResultsObject(arg1, arg2, arg3...)
Run Code Online (Sandbox Code Playgroud)

该函数执行繁重的工作并返回唯一的ID字符串(存储在持久散列中的对象的键).单元格A1现在包含此字符串值,然后我可以将其传递给其他函数:然后,它们可以使用键访问散列中的缓存对象.

这可能吗?如果是这样的话?

Rom*_*man 7

您在模块中声明的变量是持久的.

模块中的此代码可能会进入您想要的方向:

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
Run Code Online (Sandbox Code Playgroud)

注意:

对于重复或缺少的名称,代码将失败.可以通过相应地修改函数签名来传递任何类型的对象,而不是字符串值.

附录:

具有更多智能的相同代码 - 对于集合中的现有密钥,将替换值而不是失败并出现错误.

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
Run Code Online (Sandbox Code Playgroud)