在Visual Basic for Applications(VBA)中设置全局Scripting.Dictionary

Mar*_*ror 6 vba dictionary

我有一个附加字典的功能.只要updateList不是这样,我想保留这本词典的内容.我目前的设置如下:

Public Function runPolluxFull(voerUit As Boolean, updateList As Boolean)

Dim dicTitle As Variable
Dim dicFound As Variable

If updateList = True Then
Set dicTitle = CreateObject("Scripting.Dictionary")
Set dicFound = CreateObject("Scripting.Dictionary")

While status
        Set ObjectsJSON = jsonlibPollux.parse(responseString)

        With dicTitle
        .Add inc, ObjectsJSON.Item("title")
        End With

        With dicFound
        .Add inc, ObjectsJSON.Item("description")
        End With

Wend
End If
Run Code Online (Sandbox Code Playgroud)

如果voerUit确实如此,则会发生以下情况:

For i = 1 To dicTitle.Count
klaar = findReplace(dicTitle.Item(i), "x" + dicTitle.Item(i), dicTitle.Item(i) + vbCrLf + vbCrLf + dicFound.Item(i))
Next i
Run Code Online (Sandbox Code Playgroud)

这里的问题是当这个函数结束dicTitle并被dicFound清除时,findReplace函数被送入空参数.

反正有没有使代码工作,或一个良好的解决方法?

end*_*and 8

您需要添加对Microsoft Scripting Runtime的引用以使用我使用过的绑定.它更适合您声明它们的方式,因为您可以更好地访问对象,并且可以更轻松地查看成员变量等.

方法1 - 字典的模块级别或公共变量

您可以这样做的一种方法是为您正在使用的脚本字典创建模块级变量:

Public gDicTitle As Scripting.Dictionary
Public gDicFound As Scripting.Dictionary

Public Function runPolluxFull(voerUit As Boolean, updateList As Boolean)


    If updateList = True Then
        Set gDicTitle = New Scripting.Dictionary
        Set gDicFound = New Scripting.Dictionary

        While Status
                Set ObjectsJSON = jsonlibPollux.Parse(responseString)

                With gDicTitle
                .Add inc, ObjectsJSON.Item("title")
                End With

                With gDicFound
                .Add inc, ObjectsJSON.Item("description")
                End With

        Wend
    End If
End Function
Run Code Online (Sandbox Code Playgroud)

方法2 - 对字典的静态引用

您也可以通过使字典静态来完成此操作.这将在函数调用之间保留它们,如文档所述.

Public Function runPolluxFull(voerUit As Boolean, updateList As Boolean)
    Static gDicTitle As Scripting.Dictionary
    Static gDicFound As Scripting.Dictionary

    If updateList = True Then
        Set gDicTitle = New Scripting.Dictionary
        Set gDicFound = New Scripting.Dictionary

        While Status
                Set ObjectsJSON = jsonlibPollux.Parse(responseString)

                With gDicTitle
                .Add inc, ObjectsJSON.Item("title")
                End With

                With gDicFound
                .Add inc, ObjectsJSON.Item("description")
                End With

        Wend
    End If
End Function
Run Code Online (Sandbox Code Playgroud)