2
votes

I have a ListView that represents all FormFields in a word document, like a table of contents.

Function addFields(field As formField)
    Set oApp = GetObject(, "Word.Application")
    oApp.Visible = True
    Set oDoc = oApp.ActiveDocument
    Dim dFormField As formField
    Dim i As Integer
    For i = 1 To oDoc.FormFields().Count
        Set dFormField = oDoc.FormFields(i)
        If (dFormField Is field) Then
            Set Item = NavigatorForm.LBFields.ListItems.Add(i, , i)
            Set Item.tag = dFormField
            Exit For
        End If
    Next
End Function

How can I compare whether the FormField I'm adding, is at a certain index in the object model, and insert it in the correct place in the list?

            If (dFormField Is field) Then

Is how you compare object referential equality in vba, but it appears the DOM is creating a new formfield object each time. So either I've made an error, or I need some other method of determining whether they are the same formfield piece.

I would use the auto generated bookmark text, but it can't be relied upon to not have empty text or duplicates due to copy and paste, which doesn't update the bookmark names.

1

1 Answers

0
votes

This is my hacky solution. I will award a better solution with the answer.

Function addFields(field As formField)
    Dim orig As String
    Dim detect As String
    orig = field.Result
    field.Result = Rnd(100000)
    Set oApp = GetObject(, "Word.Application")
    oApp.Visible = True
    Set oDoc = oApp.ActiveDocument
    Dim dFormField As formField
    Dim i As Integer
    For i = 1 To oDoc.FormFields().Count
        Set dFormField = oDoc.FormFields(i)
        If (dFormField.Result = field.Result) Then
            field.Result = orig
            Set Item = NavigatorForm.LBFields.ListItems.Add(i, , i)
            Set Item.tag = dFormField
            Exit For
        End If
    Next
End Function