"entirerow.delete" 跳过 For 循环中的条目

"entirerow.delete" skips entries in For loop

我正在尝试清理一组数据,发现 vba 函数有一些奇怪的地方 entirerow.delete 以下代码将按预期删除整行(如果采用删除线格式),但将跳过紧跟其后的行(如果它们也采用该格式)。似乎需要一行不是删除线格式的行才能 "reset" 删除更多行的能力。有谁知道为什么,或者我可以做些什么来调试它?

For Each rng In rng1
'Check each character in the cell
    For i = 1 To Len(rng.Value)
'If any letter is Strikethrough,delete entire column
        If rng.Characters(i, 1).Font.Strikethrough = True Then
            rng.Select    'just serves the purpose of observing which rows are being selected
            rng.EntireRow.Delete
        GoTo NextRng
        End If
    Next i
NextRng:
Next rng

我应该说我已经找到了一个使用不同方法的解决方法,但速度很慢:

'Delete cells that have the strikethrough format - works but is super slow!
ws2.Range("B2").Activate
Do Until ActiveCell.Value = ""
    If ActiveCell.Font.Strikethrough = True Then
        ActiveCell.EntireRow.Delete
        Else: ActiveCell.Offset(1, 0).Activate
    End If
Loop

如果有人有其他方法可以快速解决此问题,我也将非常感谢您的意见。

找到范围的终点:

Dim wSheet As Worksheet : Set wSheet = ThisWorkbook.Worksheets("Sheetname")
Dim lastRow
' gets the last row in col 1, adjust as required
lastRow = wSheet.Cells(wSheet.Rows.Count, 1).End(xlUp).Row 

现在向后执行 For 循环。您面临的问题是,当您删除一行时,数据会向上移动(例如:第 56 行被删除,第 57 行变为 56)。解决方法是从下往上删除。

For myLoop = lastRow to 2 Step -1 ' or to 1 if you've no header row
    Set myRange  = wSheet.Range("A" & myLoop)
    For mySubLoop = 1 To Len(myRange.Value)
        'If any letter is strikethrough,delete entire row 
        If myRange.Characters(mySubLoop, 1).Font.Strikethrough = True Then
            myRange.EntireRow.Delete
            Exit For ' skip out of this inner loop and move to the next row
        End If
    Next
Next

多亏了你们的快速回复,我才弄明白了。特别感谢@Siddarth Rout 在此处推动我在此线程上采用(稍微)更快的方法:VBa conditional delete loop not working 这是工作代码,以防有人好奇:

Dim delRange As Range
Dim ws2 As Worksheet
Dim i As Long

'Find Lastrow in ws2
LastRow2 = ws2.Cells.Find(What:="*", _
                After:=Range("A1"), _
                LookAt:=xlPart, _
                LookIn:=xlFormulas, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False).Row
With ws2
    For i = 1 To LastRow2
        If .Cells(i, 2).Font.Strikethrough = True Then
'This if statement adds all the identified rows to the range that will be deleted
            If delRange Is Nothing Then
                Set delRange = .Rows(i)
            Else
                Set delRange = Union(delRange, .Rows(i))
            End If
        End If
    Next i

    If Not delRange Is Nothing Then delRange.Delete
End With