如何使用 VBA 将 Word 文档中的字段替换为其内容?

How to replace Fields in Word document with their content using VBA?

一些网站使用文本区域在文章中发布代码。如果有人 copy/paste Word 中的文章,它会显示带滚动条的空文本区域,并在带有编号行的 table 代码下方显示。
我想用代码替换它(或者只用我可以成功转换为文本的 table),方法是删除文本区域。

试过这样做

Sub RemoveTextBoxes()     
    Dim oFld    As Word.FormField
     
    With Application.ActiveDocument
        ' \ TextInput Type requires to unprotect the document
        If .ProtectionType <> wdNoProtection Then .Unprotect
         
        ' \ Loop all formfields in active document
        For Each oFld In .FormFields()
             
            ' \ Only remove Formfield textboxes that have textinput only
            If oFld.Type = wdFieldFormTextInput And oFld.TextInput.Type = wdRegularText Then
             
                ' \ Delete
                oFld.Delete
            End If
        Next
         
        ' \ Reprotect the document
        .Protect wdAllowOnlyFormFields, True
    End With  
End Sub

如果我按 Alt+F9(显示域代码)我现在确实看到了

{ HTMLCONTROL Forms.HTML :TextArea.1 } 

文本框上方有滚动条!如果我关闭并再次打开,它仍然在这里。

如何获取此 TextArea 内容并用内容删除|替换元素?

Word 中的动态内容使用 "fields" 进行管理。并非所有接受输入的字段都是 "form fields",正如您在使用 Alt+F9 时发现的那样会显示字段代码。

Word 的查找/替换功能非常强大:它还可以用于查找字段,甚至是特定字段。在这种情况下,因为您只是想删除它们,所以可以找到 HTMLControl 字段并将其替换为 "nothing"。 (如果您想更具体并保留一些 HTMLControl 字段,请根据需要使用尽可能多的文本以仅删除这些字段。)

很多人没有意识到,您可以搜索域代码而不需要显示它们。查找还可以处理显示的字段结果。诀窍是将 Range.TextRetrievalMode 设置为包含字段代码(在这种情况下,我认为也包含隐藏文本是个好主意,但如果这是一个问题,请注释掉或删除该行)。

搜索文本中的 ^d 表示开始字段括号:{ - 如果省略此内容,则只会替换(删除)括号内的内容,我不建议这样做。 ^d 整个字段 - 包括右括号 - 都会受到影响。

Sub FindAndDeleteHtmlFields()
    Dim doc As word.Document
    Dim fld As word.Field
    Dim rngFind As word.Range

    Set doc = ActiveDocument
    Set rngFind = doc.content
    rngFind.TextRetrievalMode.IncludeFieldCodes = True
    rngFind.TextRetrievalMode.IncludeHiddenText = True
    With rngFind.Find
        .Text = "^d HTMLControl"
        .ClearFormatting
        .Replacement.Text = ""
        .Execute Replace:=wdReplaceAll
    End With
End Sub

请注意,这也适用于 C# - 我的印象是您实际工作的地方...