I am trying to insert a macro button form field into cell 2 but I keep getting 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
Debugger highlights the following:
Set oForm = ActiveDocument.Fields.Add(oCell.Range, Type:=wdFieldEmpty, Text:= _
"MACROBUTTON test1 - ", PreserveFormatting:=False)
Which was adapted from the recorded macro below which successfully inserts a form field by manually selecting the desired cell and running the macro
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
"MACROBUTTON test1 - ", PreserveFormatting:=False
I was looking at Getting an error trying to insert field in a Word table cell but couldn't figure out how to adapt to my code.
Your code has 2 problems. You've declared oForm as Fields, it should be Field. You're inserting a single field, not a collection. You can't insert a field into the cell range, you first have to collapse the range to a single insertion point.
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