问题
Basically, what I'm trying to accomplish is this: Delete all rows from a table starting from where the cursor is in the table to the end of the table.
The problem is that this table contains vertically merged cells, so when I try to do something like this:
For i = Selection.Tables(1).Rows.Count To Selection.Cells(1).RowIndex Step -1
Selection.Tables(1).Rows(i).Delete
Next
It complains that individual rows cannot be accessed because the table contains vertically merged cells.
I've also tried selecting the range first, and then deleting the selection. But I couldn't get the range definition right; it always complained that there was an improperly defined parameter.
回答1:
Aren't merged table cells just a pain in the rear with VBA? Word seems to get confused with the column and row count. The follow seems to be pretty robust with any combination of horizontally or vertically merged cells.
Sub DeleteRows()
Selection.MoveDown Unit:=wdLine, Count:=(Selection.Tables(1).Rows.Count - Selection.Cells(1).RowIndex), Extend:=wdExtend
Selection.Rows.Delete
End Sub
回答2:
I wanted to add an answer as I attempted CuberChase solution but it did not work with my table:

Notice I have vertically merged rows in columns 1, 2 and 5. When I implemented Selection.MoveDown
with the intent of selecting all rows within the parent "A3" row, it did not recognize the internal rows in columns 3 and 4. It instead selected the parent "A4", "A5" and "A6" rows (same format as A3) without selecting any internal rows.
Here is what I had to do in the end to successfully delete the parent and child rows in my table. I first had to collect the indices for the first cell in each row to delete into an array. I reversed my array in order to work from the bottom up so as not to change the indices at runtime.
Then I looped through my reversed array, selecting the range of cells belonging to each parent row and deleting the rows associated with my selection.
table = ActiveDocument.Tables(1)
For Each idx In ReverseArray
cells_to_delete = ActiveDocument.Range(Start=table.Range.Cells(idx).Range.Start, End=table.Range.Cells(idx+*count_of_cells*).Range.End)
cells_to_delete.Select
Selection.Range.Rows.Delete
Next idx
No idea if anyone else has come across a similar problem, but I figured I'd put the answer up here in case someone does. :)
来源:https://stackoverflow.com/questions/13818541/deleting-a-range-from-a-table-with-merged-cells