我正在为一系列文档开发解析器。作为解析的一部分,我在各个文档中放置书签,然后一次循环浏览它们,以将我真正想要的数据从包含多个实例的文档中提取出来。我在文档中感兴趣的信息有几个部分,我按顺序访问这些部分,然后将它们放入一个数组中,该数组包含一个带有数据映射的字典。出于某种原因,当我在几行之后更新用于提供字典键的变量时,字典会更新 - 在它应该更新之前的几行。当我稍后尝试添加密钥时,这会导致引发错误。如果有人能解释幻影更新,我将不胜感激。
更新:我刚刚注意到它也发生在
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