How to change the text of a form field text box on entry of that text box

前端 未结 1 1489
礼貌的吻别
礼貌的吻别 2020-12-22 06:29

I am trying to change the text of a form field text box when it is entered into. I selected to run a macro on entry, but I can\'t seem to change it dynamically for all my fi

相关标签:
1条回答
  • Every form field has a bookmark and a name, by default. They're generated by Word when the form field is inserted and the names for text fields follow the pattern Text1, Text2, and so on.

    While Selection doesn't return the form field when an "On Enter" macro is triggered it does return the bookmark. Through that, it's possible to get the bookmark name and from there access the form field. So:

    Sub WriteValueToFormFieldOnEnter()
        Dim bkm As Word.Bookmark
        Dim ffldName As String, ffld As Word.FormField
    
        If Selection.Bookmarks.Count > 0 Then
            Set bkm = Selection.Bookmarks(1)
            ffldName = bkm.Name
            Set ffld = ActiveDocument.FormFields(ffldName)
            ffld.result = "New"
        End If    
    End Sub
    

    Note: If the form fields have no bookmark name because they were copied/pasted within the same document, then names have to be assigned to the form fields. (Bookmark names must be unique within a document, which is why this happens.) The following code loops the formfields in a document and assigns those with no name a name.

    While the Language Reference for FormField.Name states

    Returns a String that represents the result of the specified form field. Read/write.

    writing to this property causes an error (at least in Word 2010 and newer, perhaps also in older versions). So it's necessary to work with the Word UI's Form Field Properties dialog box.

    Sub NameUnnamedFormFields()
        Dim ffld As Word.FormField
        Dim rng As Word.Range
        Dim tbCounter As Long, cbCounter As Long, ddCounter As Long
    
        tbCounter = 1: cbCounter = 1: ddCounter = 1
        For Each ffld In ActiveDocument.FormFields
            If Len(ffld.Name) = 0 Then
                ffld.Select
                With Application.Dialogs(wdDialogFormFieldOptions)
                    Select Case ffld.Type
                        Case wdFieldFormTextInput
                            .Name = "myText" & CStr(tbCounter)
                            tbCounter = tbCounter + 1
                        Case wdFieldFormCheckBox
                            .Name = "myCheckBox" & CStr(cbCounter)
                            cbCounter = cbCounter + 1
                        Case wdFieldFormDropDown
                            .Name = "myDropDown" & CStr(ddCounter)
                            ddCounter = ddCounter + 1
                        Case Else
                            MsgBox "Unknown form field type."
                    End Select
                    .Execute
                End With
            End If
        Next
    End Sub
    
    0 讨论(0)
提交回复
热议问题