How to insert MergeField into a specific table cell using VBA?

I am working in Word 2007. I am trying to insert a mergefield into a specific cell (that is, the first cell of the second row), but without success. With a simple mergefield insert, 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 a cell, it throws an error:

Runtime Error "4605". Command not available.

This is the code 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 the same. How to insert mergefield field in table cell using VBA script?

+4
source share
1 answer

, , , . , .

:

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
+3

Source: https://habr.com/ru/post/1542623/


All Articles