在保存键的变量更新时更新字典对象



我正在为一系列文档编写解析器。作为解析的一部分,我在各个文档中放置书签,然后逐个遍历它们,从包含多个实例的文档中提取实际需要的数据。我在文档中感兴趣的信息有几个部分,我依次访问它们,然后将它们放入一个数组中,该数组包含一个带有数据映射的Dictionary。由于某种原因,当我在几行之后更新用于向字典提供键的变量时,字典会提前几行更新。这将导致在几行之后尝试添加键时抛出错误。如果有人能解释幻影升级的原因,我会很感激。

更新:我刚刚注意到它也发生在

之后
Set Topics(TopicsCount).TopicMap = New Scripting.Dictionary

当CurrentString值第一次为"Title"时,甚至在我调用Add

之前
Sub ParseDoc()
Dim objDoc As Document
Set objDoc = ActiveDocument
Dim Topics() As TopicData
Dim TopicsCount As Integer
TopicsCount = -1
Dim DataRange As Range
For i = 1 To objDoc.Bookmarks.count - 1
    indexOfBase = InStr(1, objDoc.Range.Bookmarks(i), "Base")
    CurrentString = Left(objDoc.Range.Bookmarks(i), indexOfBase - 1) ' after this line the Topices(TopicCount).TopicMap updates
    If CurrentString = "Title" Then
        TopicsCount = TopicsCount + 1
        ReDim Preserve Topics(TopicsCount)
        Set Topics(TopicsCount) = New TopicData
        Topics(TopicsCount).TopicID = GrabTitle
        Set Topics(TopicsCount).TopicMap = New Scripting.Dictionary 'the Map will update here the first time with CurrentString, note that the add line is further down and the Map shouldn't know about CurrentString yet.'
    End If
    Set DataRange = ActiveDocument.Range(Start:=objDoc.Range.Bookmarks(i).End, End:=objDoc.Range.Bookmarks(i + 1).Start)
    If CurrentString = "TechArea" Or CurrentString = "Keywords" Then
        DataArray = Split(DataRange.Text, ",")
        For j = 0 To UBound(DataArray)
            DataArray(j) = Trim(DataArray(j))
        Next j
        Topics(TopicsCount).TopicMap.Add CurrentString, DataArray ' throws error because of earlier update
    Else
        Topics(TopicsCount).TopicMap.Add CurrentString, DataRange.Text ' thorws error because of earlier update
    End If
    Next i
End Sub

不管什么原因,这已经不再是一个问题了。谢谢大家的帮助,但就像这个问题开始时一样神秘,它停止了。

Update -这个问题实际上似乎与调试有关。只有当调试器在字典行之前遇到断点时,才会出现这种情况。显然,当我遇到断点时,VBA会以某种方式自动填充它(至少使用0索引项)。

相关内容

  • 没有找到相关文章

最新更新