Search code examples
vbadictionaryms-wordword-2013

Dictionary object updating at when the variable holding the key is updated


I am working on a parser for a series of documents. as part of that parsing I place bookmarks throughout the individual documents and then cycle through them one at a time to pull the data I actually want out of the document which has several instances in it. The information I am interested in within the document has several parts that I access sequentially and then throw into an array that holds a Dictionary with the data mappings. for some reason, when I update the variable that is being used to provide the key to the dictionary a few lines later, the dictionary updates - several lines before it should. This causes an error to be thrown when I try to add the key a few lines later. If anybody can explain the phantom updating I'd be grateful.

Update: I just noticed that it also happens after the

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

when the CurrentString value is "Title" the 1st time, before I have even called 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

Solution

  • for whatever reason this has ceased to be a problem. thanks for the help people, but just as mysteriously as this problem started, it stopped.

    Update - the problem actually seems to be related to debugging. It only appears to happen when the debugger hits a breakpoint prior to the dictionary line. apparently VBA was auto populating it somehow (at least with a 0 index item)when I would hit the breakpoint.