Word- VBA- 如何将宏按钮表单字段插入 Table 单元格?

Word- VBA- How To Insert Macro Button Form Field Into Table Cell?

我正在尝试将宏按钮表单字段插入单元格 2,但我一直收到 Run-Time Error '4605': This method or property is not available because the drawing operation cannot be applied to the current selection

Dim oTable As Table
Dim ocell As Cell
Dim oCC As ContentControl
Dim oForm As Fields

Dim oNewRow As Row
    Set oTable = ActiveDocument.Tables(1)
    Set oNewRow = oTable.Rows.Add
    Set ocell = oNewRow.Cells(1)
    Set oCC = ActiveDocument.ContentControls.Add(wdContentControlRichText, oCell.Range)
    
    Set oCell = oNewRow.Cells(2)
    Set oForm = ActiveDocument.Fields.Add(oCell.Range, Type:=wdFieldEmpty, Text:= _
        "MACROBUTTON  test1 - ", PreserveFormatting:=False)
lbl_Exit:
    Exit Sub

调试器突出显示以下内容:

Set oForm = ActiveDocument.Fields.Add(oCell.Range, Type:=wdFieldEmpty, Text:= _
        "MACROBUTTON  test1 - ", PreserveFormatting:=False)

改编自下面录制的宏,通过手动选择所需的单元格和 运行 宏

成功插入表单域
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
        "MACROBUTTON  test1 - ", PreserveFormatting:=False

我正在查看 但无法弄清楚如何适应我的代码。


您的代码有 2 个问题。 您已将 oForm 声明为字段,它应该是 Field。您插入的是单个字段,而不是集合。 您不能将字段插入单元格范围,您首先必须将范围折叠为单个插入点。

Dim oTable As Table
Dim ocell As Cell
Dim oCC As ContentControl
Dim oForm As Field
Dim oRange as Range

Dim oNewRow As Row
    Set oTable = ActiveDocument.Tables(1)
    Set oNewRow = oTable.Rows.Add
    Set ocell = oNewRow.Cells(1)
    Set oCC = ActiveDocument.ContentControls.Add(wdContentControlRichText, oCell.Range)
    
    Set oRange = oNewRow.Cells(2).Range
    oRange.Collapse Direction:=wdCollapseStart
    Set oForm = ActiveDocument.Fields.Add(oRange, Type:=wdFieldEmpty, Text:= _
        "MACROBUTTON  test1 - ", PreserveFormatting:=False)
lbl_Exit:
    Exit Sub