简体   繁体   中英

Reset formfields corrupts Word document

I have a large, dynamic Word macro with lots of formfields on it. It takes a long time to run, and by far the most time consuming part is clearing all the formfields before mapping them. Right now I'm looping through them and setting them individually = "". I found a quicker way to do it, but it always corrupts the document.

1) Current:

For Each fld In doc.FormFields
    If fld.Type = wdFieldFormTextInput And fld.Result <> "" Then
        fld.Result = ""
    ElseIf fld.Type = wdFieldFormCheckBox Then
        fld.CheckBox.Value = False
    End If
Next

2) Tried:

ActiveDocument.ResetFormFields

and 3)

Unload Me

in a command button click event

1) Takes at least a minute every time 2) is almost instant but corrupts the document (error saying "Word has encountered a problem. You will not be able to undo this action...") 3) Throws an error- "361: Can't load or unload this object"

I either want 2) to work, or to find any faster way to clear the formfields. Thanks for your time.

Referring to (2): this is not so much an error message as a warning, and there's no document corruption. Word always loses the Undo list when a document is unprotected, which is what happens behind the scenes with this method.

Two approaches occur to me. One would be to disable alerts, which should suppress the warning. The other would be to emulate the user action of unprotecting, then re-protecting without saving the current form field entries.

To suppress the warning (this won't affect true error messages):

Application.DisplayAlerts = wdAlertsNone 

To unprotect then reprotect the document without saving user input:

Sub UnprotectReprotectToResetFields()
    Dim doc As Word.Document

    Set doc = ActiveDocument

    If doc.ProtectionType <> wdNoProtection Then
        doc.Unprotect
    End If
    doc.Protect wdAllowOnlyFormFields, False

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM