我想将快捷键关联到可以在Word文档的某些表上使用的VBA宏。 此宏应遍历所选表的所有行,并删除具有特定Shading.BackgroundPatternColor
的行。我尝试了以下代码:
Sub DeleteRowWithShading()
Dim oRow As Word.Row
For Each oRow In Selection.Rows
If oRow.Shading.BackgroundPatternColor = -721354855 Then
oRow.Delete
End If
Next oRow
End Sub
遍历表的所有行都是正确的,但是没有按预期删除行。
我对VBA还是很陌生,因此感谢您的帮助!
答案 0 :(得分:0)
在循环中删除集合的元素时,会出现问题。删除操作会从集合中删除该项目,从而使内部计数不正确。
有两种基本方法可以解决此问题。
1)从头到尾遍历所有项目。由于从集合中删除的内容是最后的,因此不会浪费时间:
Sub DeleteRowWithShading()
Dim oRow As Word.Row
Dim tbl As Word.Table
Dim nrRows As Long, rowCounter As Long
Dim check As Long
Set tbl = Selection.Tables(1)
nrRows = tbl.Rows.Count
For rowCounter = nrRows To 1 Step -1
Set oRow = tbl.Rows(rowCounter)
If oRow.Shading.BackgroundPatternColor = -721354855 Then
check = check + 1
oRow.Delete
End If
Next
Debug.Print "Nr of rows deleted: " & check
End Sub
2)在第一个循环中将项目添加到数组或自定义集合中,然后循环该数组/集合以删除所有项目(行)。
Sub DeleteRowWithShadingInArray()
Dim oRow As Word.Row
Dim tbl As Word.Table
Dim RowsToDelete() As Variant
Dim check As Long, itemNr As Long
Set tbl = Selection.Tables(1)
itemNr = 0
For Each oRow In tbl.Rows
ReDim Preserve RowsToDelete(itemNr)
If oRow.Shading.BackgroundPatternColor = -721354855 Then
Set RowsToDelete(itemNr) = oRow
itemNr = itemNr + 1
End If
Next
itemNr = 0
For itemNr = 0 To UBound(RowsToDelete)
check = check + 1
RowsToDelete(itemNr).Delete
Next
Debug.Print "Nr of rows deleted: " & check
End Sub