" entirerow.delete"跳过For循环

时间:2016-09-21 15:24:10

标签: vba excel-vba for-loop delete-row strikethrough

我试图清理一组数据并注意到vba函数的一些奇怪问题wholerow.delete 如果格式为删除线,则以下代码将按预期删除整行,但如果它们也采用该格式,则会跳过紧随其后的行。这似乎是一个不是采用删除线格式的行来重置"重置"删除更多行的能力。有谁知道为什么,或者我可以做些什么来调试这个?

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

如果有人有另一种方法来解决这个问题也很快,我也非常感谢您的意见。

2 个答案:

答案 0 :(得分:2)

感谢您的所有快速回复,我明白了。特别要感谢@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

答案 1 :(得分:0)

查找范围的结尾:

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