How do I insert MergeField into specific table cell with VBA?
ms-word, vba
Solution
In my opinion when you select cell inside table the selection includes end-cell mark which could not be replaced with the field. You need to select cell range which doesn't include that final mark.
I suggest the following improvement of your code:
Dim collectTable As Table
Set collectTable = ActiveDocument.Tables(1)
'selecting cell range without cell-end mark
ActiveDocument.Range(collectTable.Cell(1, 1).Range.Start, _
collectTable.Cell(1, 1).Range.End - 1).Select
Selection.Fields.Add Selection.Range, _
Type:=wdFieldEmpty, _
Text:="MERGEFIELD $!testField", _
PreserveFormatting:=True
Problem
I work in Word 2007. I am trying to insert a mergefield into specific cell (i.e first cell of the second row), but without success. With simple inserting mergefield I have no problem: ``` Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _ "MERGEFIELD $!test ", PreserveFormatting:=True ``` But when I try to insert mergefield into cell it throws an error: Run-time error '4605'. The command is not available. This is the code what I tried: ``` collectTable.Cell(1, 1).Select Selection.Fields.Add Selection.Range, Type:=wdFieldEmpty, Text:="MERGEFIELD $!testField", PreserveFormatting:=True ``` and also I tried this: ``` collectTable.Cell(1, 1).Select Selection.Fields.Add collectTable.Cell(1, 1).Range, Type:=wdFieldEmpty, Text:="MERGEFIELD $!testField", PreserveFormatting:=True ``` But the result is same. How can I insert a mergefield in table cell with VBA script?