0
votes

I am working on an Outlook VBA macro that updates existing Word documents. I would like to update the default value of some existing form fields with VBA code but I cannot figure out how.

FormFields("fieldName").Result = myNewValue is not working : after a refresh (Ctrl+A then F9) the written values are deleted.

I know I can easily do it with custom document properties but it would be more convenient for me to use form fields instead.

Is there ANY way I can update the form field default values?

2

2 Answers

2
votes

The Result property is what the user types - not what you're looking for.

What you need is the TextInput.Default property. The catch with this, however, is that it won't display in the document until the field is updated. This means you will have to unprotect the form, if your code isn't already doing that.

Sub ChangeFormFieldDefault()
    Dim doc As word.Document
    Dim ffld As word.FormField
    Dim rngFFld As word.Range
    Dim countFields As Long

    Set doc = ActiveDocument
    Set ffld = doc.FormFields("Text1")
    Set rngFFld = ffld.Range
    countFields = doc.Range(doc.content.Start, rngFFld.End).Fields.Count
    ffld.TextInput.Default = "default text"
    'for the following form field protection must be turned off
    doc.Fields(countFields).Update
End Sub
2
votes

The fact your formfield is losing its result when you do Ctrl+A, F9 shows your document doesn't have 'filling in forms' protection applied. In that case, you could use either:

With ActiveDocument.FormFields(1)
  .TextInput.Default = "Hello world"
  .Result = .TextInput.Default
End With

or:

With ActiveDocument
  .FormFields(1).TextInput.Default = "Hello world"
  .Fields.Update
End With