0
votes

I'm trying to create a macro in Word 2013 that searches for a text in the first column of a table and replaces it with a Quick Part. I created the following:

Sub set_icons()
    Dim t As Table
    Dim r As Row
    Dim cellText As String

    For Each t In ActiveDocument.Tables
        For Each r In t.Rows
            cellText = r.Cells(1).Range.Text
            cellText = Trim(cellText)
            If cellText = "text to match" Then
                ActiveDocument.AttachedTemplate.BuildingBlockEntries("testtest").Insert r.Cells(1).Range
                Debug.Print "yes"
            End If
        Next
    Next
End Sub

This code results in an error:

Runtime error '-2147467259 (80004005)':
Method 'Insert' of object 'BuldingBlock' failed.

If I change r.Cells(1).Range to Selection.Range the Quick Part is entered in the document. But I somehow can't add it in a table cell.

1
I haven't verified it for this particular case, but a frequent problem with working with the range of a cell is that an operation tries to replace the cell end marker, and since it cannot be deleted, the operation fails.user1379931

1 Answers

1
votes

This seems to work:

Dim myRange As Word.Range    

Set myRange = ActiveDocument.Range(r.Cells(1).Range.Start, r.Cells(1).Range.Start)
ActiveDocument.AttachedTemplate.BuildingBlockEntries("testtest").Insert myRange