In Excel VBA how to persist key variables over a 'state loss' (without writing to a cell or a file)?

后端 未结 2 624
长情又很酷
长情又很酷 2020-12-06 08:17

Excel VBA is a flexible development environment. It is pesudo-compiled. However, sometimes during development a \"state loss\" can occur. A \"state loss\" is when all var

2条回答
  •  粉色の甜心
    2020-12-06 08:51

    One way to keep the data persistent during the lifetime of Excel is to store them on the default .Net domain attached to the instance:

    Sub Usage()
        Dim dict As Object
        Set dict = GetPersistentDictionary()
    End Sub
    
    Public Function GetPersistentDictionary() As Object
        ' References:
        '  mscorlib.dll
        '  Common Language Runtime Execution Engine
    
        Const name = "weak-data"
        Static dict As Object
    
        If dict Is Nothing Then
          Dim host As New mscoree.CorRuntimeHost
          Dim domain As mscorlib.AppDomain
          host.Start
          host.GetDefaultDomain domain
    
          If IsObject(domain.GetData(name)) Then
            Set dict = domain.GetData(name)
          Else
            Set dict = CreateObject("Scripting.Dictionary")
            domain.SetData name, dict
          End If
        End If
    
        Set GetPersistentDictionary = dict
    End Function
    

提交回复
热议问题