2016-09-21 139 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