Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop Word from selecting each FormField as I read their values in VBA?

Tags:

ms-word

vba

I have a template document in Word 2013 that has the user fill in a large number of Legacy Text FormFields. At the end of the document, I've included a button which compiles the answers into a string devoid of formatting, then copies it to the clipboard.

It works, but as each FormField is read, the Word document skips back and forth between each text field and the end of the document. It's visually alarming. Is there a way to gather the values of each FormField without Word moving the cursor/focus to each field as it is read?

Here's a sample of the code:

Private Sub cmdCreateNote_Click()

    Call cmdClearNote_Click

    Dim ff As FormFields
    Set ff = ActiveDocument.FormFields

    Dim Output As String
    Output = ff("ddReviewType").Result & vbCrLf

    If ff("chFacInfo").Result Then
        Dim FacInfo
        FacInfo = Array("Field1: ", _
            "Field2: ", _
            "Field3: ", _
            "Field4: ", _
            "Field5: ")

        Output = Output & "FIRST SECTION" & vbCrLf

        For Index = 1 To 5
            If ff("chFacInfo" & Index).Result Then
                Output = Output & FacInfo(Index - 1) & ff("txFacInfo" & Index).Result & vbCrLf
            End If
        Next

        Output = Output & vbCrLf
    End If

    Dim FORange As Range
    Set FORange = ActiveDocument.Bookmarks("FinalOutput").Range
    FORange.Text = Output
    ActiveDocument.Bookmarks.Add "FinalOutput", FORange

    Selection.GoTo What:=wdGoToBookmark, Name:="FinalOutput"
    Selection.Copy

End Sub

It appears that every time I access ActiveDocument.FormFields( x ).Result, the document focus goes to that element, then drops back to the end of the document again.

Any pointers?

like image 491
Kapulani Avatar asked Sep 30 '22 21:09

Kapulani


1 Answers

Use the Bookmark object instead of the FormField. This will allow you to access the properties without changing the screen focus. See answer on Suppress unwanted jumping/scrolling on Word 2013 VBA Script for specifics on how to do this.

ActiveDocument.Bookmarks("myFieldName").Range.Fields(1).Result
like image 87
AdamsTips Avatar answered Oct 07 '22 19:10

AdamsTips