在docx文件的宏中通过索引以编程方式删除重复节项目?

时间:2016-08-19 01:25:24

标签: vba ms-word word-vba docx

我有一个单词模板,内容控件包含在重复部分内容控件中。我需要创建一个按钮来删除项目转发器,例如添加。

我想弄清楚如何删除重复的部分项目。但在这种情况下 - 我总是删除最后一项。但是,我希望能够删除用户选择的项目。

Sub delete()
    Dim cc As ContentControl
    Dim Index
    Set cc = ThisDocument.SelectContentControlsByTag("ResolRepeater").Item(1)
    With cc
        .LockContentControl = False
        .LockContents = False
        .AllowInsertDeleteSection = True

        For Index = 1 To cc.RepeatingSectionItems.Count
        If Selection.Range.InRange(cc.RepeatingSectionItems(Index).Range) Or cc.RepeatingSectionItems(Index).Range.InRange(Selection.Range) Then
           Exit For
        End If
        Next Index

        'can't delete, get Run-Time Error '5904': "you can not change the range"
        cc.RepeatingSectionItems(Index).Range.delete

        'this lines always delete last element:
        'cc.RepeatingSectionItems(Index).Range.Select 
        'Selection.Delete

    End With 
End Sub

word template

我很乐意回答任何问题。

1 个答案:

答案 0 :(得分:1)

您可以通过多种方式执行此操作,其中一种方法是处理ContentControlBeforeDelete事件MSDN Link

或者,您可以使用当前的Selection.range,检查范围(包括开头和结尾)是否具有类型wdContentControlRepeatingSection的内容控件,然后只需删除控件。

像(未经过测试的代码):

var contentControl = Selection.Range.ContentControls;
if (contentControl.Type == Microsoft.Office.Interop.Word.WdContentControlType) 
{
    contentControl.Delete();
}
相关问题