What is the best VBA data type`key`=>`value` to save data same as PHP array

六月ゝ 毕业季﹏ 提交于 2021-02-17 21:31:34

问题


I'm working with VBA and need to save data in type key=>value to getting fastest; This data type help me cache responese text from http request, increase query speed. But I don't know what is the best way to do it? I need a data type same as php array with key=>value! Thank for help!


回答1:


Have you looked at dictionary object?

It's available as part of the Microsoft Scripting Runtime. A clear example of how to add this is given by this 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

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




回答2:


Above answer will not work because of wrong syntax you need to add Scripting Keword before also enable Microsoft Sripting Run Time I tried it with and Without Sripting. before Dictionary in MS word(2016) and without dosen't work even if you have enabled Microsoft Scripting runtime

 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"


来源:https://stackoverflow.com/questions/11463799/what-is-the-best-vba-data-typekey-value-to-save-data-same-as-php-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!