Word宏在表格单元格中插入快速部分

时间:2015-10-30 13:46:26

标签: vba ms-word

我正在尝试在Word 2013中创建一个宏,该宏在表的第一列中搜索文本并将其替换为快速部分。我创建了以下内容:

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

此代码导致错误:

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

如果我将r.Cells(1).Range更改为Selection.Range,则在文档中输入快速部分。但我不知道怎么办不能把它添加到表格单元格中。

1 个答案:

答案 0 :(得分:1)

这似乎有效:

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