vbams-wordword-table

Fast way to delete many rows in a word-table using vba


i'm trying to delete around 5k table entries in a word table with 2 columns.

The problem is, when I'm using

Function ClearTable(tbl As table)
Dim i As Integer

For i = tbl.Rows.Count To 2 Step -1
    tbl.Rows(i).Delete
Next i
    
End Function

it takes forever. I tried to just select the range from the cells (2,1) to (tbl.rows.count,2) and then use the .delete function, but that only empties the entries and does not remove the entire rows.

This issue seems kinda easy to handle, but I can't figure it out currently.

Thanks in advance for any hints.

Update:

Function ClearTable(tbl As table)
Dim myCells As Range
Set myCells = ActiveDocument.Range(Start:=tbl.Cell(2, 1).Range.Start, _
            End:=tbl.Cell(tbl.Rows.Count, 2).Range.End)

myCells.Select
Selection.Rows.Delete

End Function

does what I wanted. Thanks to Timothy.


Solution

  • Using Selection is slow and unnecessary. All you need is:

    Function ClearTable(Tbl As Table)
    ActiveDocument.Range(Tbl.Rows(2).Range.Start, Tbl.Range.End).Rows.Delete
    End Function