14

我正在使用 VBA,需要将数据保存在 type key=>value中以获得最快的速度;这种数据类型帮助我缓存来自 http 请求的响应文本,提高查询速度。但我不知道最好的方法是什么?我需要一个与 php 数组相同的数据类型key=>value!感谢您的帮助!

4

2 回答 2

23

你看过字典对象吗?

它作为 Microsoft Scripting Runtime 的一部分提供。这个 SO answer给出了一个如何添加它的清晰示例。

Sub DictExample1()

Dim dict As Dictionary
Dim v As Variant

    'Create the dictionary          
    Set dict = New Dictionary

   'Add some (key, value) pairs
    dict.Add "John", 34
    dict.Add "Jane", 42
    dict.Add "Ted", 402

    'How many items do we have?
    Debug.Print "Number of items stored: " & dict.Count

    'We can retrieve an item based on the key
    Debug.Print "Ted is " & dict.Item("Ted") & " years old"


   'We can test whether an item exists
    Debug.Print "We have Jane's age: " & dict.Exists("Jane")
    Debug.Print "We have Zak's age " & dict.Exists("Zak")

    'We can update a value by replacing it
   dict.Item("Ted") = dict.Item("Ted") / 10

    Debug.Print "Ted's real age is: " & dict.Item("Ted")

   'We can add more items
    dict.Add "Carla", 23

   'And we can iterate through the complete dictionary
    For Each v In dict.Keys
        Debug.Print "Name: " & v & "Age: "; dict.Item(v)
    Next

End Sub

(来源:http ://www.techbookreport.com/tutorials/vba_dictionary.html )

于 2012-07-13T03:40:34.397 回答
1

由于语法错误,上述答案将不起作用,您需要在启用 Microsoft Sripting Run Time 之前添加 Scripting Keword 我尝试了使用和不使用 Sripting。在 MS word(2016) 中的字典之前,即使您启用了 Microsoft 脚本运行时,也无法正常工作

 Dim dict As Scripting.Dictionary
 Set dict = New Scripting.Dictionary
 dict.Add "John", 34
 dict.Add "Jane", 42
 dict.Add "Ted", 402

 Debug.Print "Number of items stored: " & dict.Count
 Debug.Print "Ted is " & dict.Item("Ted") & " years old"
于 2020-12-10T20:05:57.037 回答