0

I need to download a word document and edit the fields it contains to generate a final document with the input data from a form.

The word document contains lot of MERGEFIELD and conditionals that I need to update with new values. I have tried to loop through the fields and when the mergefield belongs to my list of valid fields, replace the value; but it doesn't work with the mergefields contained by the conditionals.

For simple it works:

Das blablabla zwischen { MERGEFIELD HerrnFrau } { MERGEFIELD Titel } { MERGEFIELD Nachname } ....

For conditional doesn't:

{ IF { MERGEFIELD property } = "yes" { MERGEFIELD HerrnFrau} ....

Dim objWord As Word.Application
Dim objDoc As Word.document
Dim objField As Word.field
Dim idx As Integer

Dim idxField As Long
idxField = 1
With objDoc
    For Each objField In .Fields
        ' Special case
        If objField.Code = " MERGEFIELD hlp_Abs2 " Then
            idx = GetIndexValue(objField.Code, AllFields)
            objField.result.text = "1"
        Else
            ' Check array with field names
            If IsInArray(objField.Code, AllFields) Then
                idx = GetIndexValue(objField.Code, AllFields)
                objField.result.text = AllValues(idx)
            End If
        End If

    Next objField
End With

What would be the proper way to update the fields of the document so the conditional content is also correctly updated?

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
blfuentes
  • 2,731
  • 5
  • 44
  • 72
  • Delete the entire IF field and insert your data in its place. BUT note that this approach is *not* the correct way to use mergefields and, should for some reason the fields would update before you do whatever is done with the document after your code has finished with it, the values being written to it with `result.text` will be lost. Better to remove the fields entirely and write the content as static text in their place. – Cindy Meister Mar 09 '20 at 17:00
  • Better still, since the code can undoubtedly text whatever you're trying to write to {MERGEFIELD property}, why don't you simply do the test in code and write the entire conditional string to the document? It would also make far more sense to use bookmarks for this than mergefields. – macropod Mar 10 '20 at 09:59

0 Answers0