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

标签 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

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

这里的问题是当这个函数结束时,dicTitledicFound被清除,findReplace函数得到空参数。

无论如何,有没有使代码工作,或者一个好的解决方法?

最佳答案

您需要添加对 Microsoft Scripting Runtime 的引用才能像我使用的那样使用绑定(bind)。它比您声明它们的方式更可取,因为您可以更好地访问对象并且可以更轻松地查看成员变量等。
方法 1 - 字典的模块级或公共(public)变量
一种方法是为您正在使用的脚本字典创建模块级变量:

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
方法 2 - 对字典的静态引用
您也可以通过制作字典 static 来做到这一点。 .如文档所述,这将在函数调用之间保留它们。
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

关于vba - 在 Visual Basic for Applications (VBA) 中设置全局 Scripting.Dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22382729/

相关文章:

EXCEL VBA - 遍历列中的单元格,如果不为空,则将单元格值打印到另一列

Excel - 查找和替换多个单词

html - VBA获取元素的父节点

vba 如果组合框选择等于 "Location",则写入 "Loc"

python - 从字符串 [Python] 创建多级字典

python - 在 Python 中将列表对转换为键值对

vba - 如何超链接 Visio 字符对象

indexing - 在 RavenDB 中查询嵌套字典

python从嵌套字典中获取最小/最大值

python - Python 中的哈希表