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

StackOverflow https://stackoverflow.com/questions/23425175

  •  14-07-2023
  •  | 
  •  

سؤال

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?

هل كانت مفيدة؟

المحلول 2

Posting comment as answer, since it worked!

Try Application.ScreenUpdating = False before going through the FormFields and then setting it to True after, in order to minimize screen updating.

نصائح أخرى

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top