简体   繁体   English

解析 VBA 字典中的数组项时下标超出范围 - 不能使用索引 0

[英]Subscript Out Of Range when parsing array items in VBA dictionary - index 0 cannot be used

I created a text file with 1 line which looked like this {"key 1":["item1","item2"],"key 2":"ItemX"} and saved it as test.json.我创建了一个包含 1 行的文本文件,看起来像这样{"key 1":["item1","item2"],"key 2":"ItemX"}并将其保存为 test.json。 I then tried parsing the items in the array in "key 1", using the VBA subroutine below:然后我尝试使用下面的 VBA 子例程解析“key 1”中数组中的项目:

Sub testjs3()
    Dim FSO As New FileSystemObject
    Dim JsonTS As TextStream
    Dim JsonText As String
    Dim Parsed As Scripting.Dictionary

    Set JsonTS = FSO.OpenTextFile("C:\test.json", ForReading)
    JsonText = JsonTS.ReadAll
    JsonTS.Close
    Debug.Print JsonText
    Set Parsed = JsonConverter.ParseJson(JsonText)
    
    Debug.Print Parsed.Item("key 1")(0)
    Debug.Print Parsed.Item("key 1")(1)

End Sub

The line Debug.Print Parsed.Item("key 1")(0) caused VBA to return Subscript Out Of Range error, whereas if I commented out that faulty line, the next line that parsed "key 1" for item at index 1 seemed to return the first item in the array which in this case was "item1". Debug.Print Parsed.Item("key 1")(0)导致 VBA 返回 Subscript Out Of Range 错误,而如果我注释掉该错误行,则下一行为索引 1 处的项解析“key 1”似乎返回数组中的第一个项目,在这种情况下是“item1”。 I can't figured out why index 0 was returning error.我不明白为什么索引 0 返回错误。

I then used another subroutine that created the dictionary instead of reading it from a json file, the subroutine is as below:然后我使用了另一个创建字典的子程序,而不是从 json 文件中读取它,子程序如下:

Sub test4()
 Dim keywords As Object
    
    Set keywords = CreateObject("scripting.dictionary")
    
    keywords.Add "key 1", Array("item1", "item2")
    keywords.Add "key 2", "ItemX"
    
    Debug.Print keywords.Item("key 1")(0)
    Debug.Print keywords.Item("key 1")(1)
    Debug.Print keywords.Item("key 2")
    
    Debug.Print JsonConverter.ConvertToJson(keywords)
        
End Sub

This time the dictionary returned the correct item in the array of "key 1" using index 0, and the debug print also showed both json strings read from the file and the one created via dictionary .add command were identical.这次字典使用索引 0 返回了“key 1”数组中的正确项目,并且调试打印还显示从文件中读取的 json 字符串和通过字典 .add 命令创建的字符串是相同的。

I am sure I missed something, your advice is very much appreciated.我确定我错过了一些东西,非常感谢您的建议。

Alex has the answer.亚历克斯有答案。 The array returned in JsonConverter.ParseJson is of type Collection which starts from index 1, whereas the array created via dictionary object .add method is of type 0-based array which starts from index 0. JsonConverter.ParseJson返回的数组是从索引 1 开始的 Collection 类型,而通过字典对象.add方法创建的数组是从索引 0 开始的基于 0 的数组类型。 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM