2016-09-21 135 views
1

我试图清理一组数据,并发现一些奇怪的vba功能wholerow.delete 下面的代码将按预期删除整行,如果它是采用删除线格式,但会跳过紧跟其后的行,如果它们也是这种格式。它看起来像一个不是以删除线格式的行来“重置”删除更多行的能力。有谁知道为什么,或者我能做些什么来调试呢?“entirerow.delete”跳过For循环的条目

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 

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

+3

环落后,如果你删除行。 – Comintern

+1

您不应该像这样删除循环中的行。使用反向循环。搜索stackoverflow。我已经在 –

+0

之前回复了一篇文章,请参阅我的[post](http://stackoverflow.com/questions/19241905/vba-conditional-delete-loop-not-working)您还可以使用范围对象来标识您想要的行删除。它比删除循环中的行快得多 –

回答

1

感谢您的所有快速响应,我明白了。特别感谢@Siddarth溃败的轻推我向(略)更快的方法在此线程在这里: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 
+0

++良好的工作到达解决方案:) –

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 
+2

你的循环中有一个错字。它应该阅读“步骤-1”。 – 2016-09-21 15:55:37

+0

@ThomasInzina感谢您的接触,非常感谢! – Dave