简体   繁体   中英

Word macro to insert Quick Part in table cell

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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM