Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete repeating section item programmatically by index in macros of docx file?

Tags:

ms-word

vba

docx

I have a word template with a content controls wrapped inside a repeating section content control.I need to create a button to delete items repeater, such as the addition of.

I'm trying to figure out how to delete a repeating section item. But in this case - I delete always the last item. But, I want to be able to remove the item the user has chosen.

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

I will be glad to any answer..

like image 714
Kseniya Yudina Avatar asked Nov 08 '22 10:11

Kseniya Yudina


1 Answers

You could do this a number of ways, one of which would be to handle the ContentControlBeforeDelete event MSDN Link

Alternatively, you could use the current Selection.range, check if the range (include the start and end) have a content control of type wdContentControlRepeatingSection and then simply delete the control.

Something like (code not tested):

var contentControl = Selection.Range.ContentControls;
if (contentControl.Type == Microsoft.Office.Interop.Word.WdContentControlType) 
{
    contentControl.Delete();
}
like image 107
Hexie Avatar answered Dec 25 '22 02:12

Hexie