Excel VBA循环删除行不以某些东西开始

我有一些工作中的数据看起来像这样:

00 some data here... 00 some data here... 00 some data here... 00 some data here... Other data I want to remove Other data I want to remove Other data I want to remove Other data I want to remove 00I also want to remove 002 some other data I want to remove 003 remove this as well 

我想删除所有不以00(空格)开头的行。 但是我的function并没有删除所有的(只有一些)。 有错字还是错误?

观察:我的代码会在每次运行中删除几行,如果我运行这个4-5次,它最终会删除所有这些。

 Sub ProcessRemittance() Dim remitDate, remitNumber, myString, tempString As String Dim myRange, cell As Range Dim StringArray As Variant Set myRange = Range("A1:A500") ' Remove all the empty rows in the worksheet myRange.SpecialCells(xlCellTypeBlanks).EntireRow.Delete ' Clean up every row does not belong to invoices For Each cell In myRange myString = Left(cell.Value, 3) If myString <> "00 " Then cell.EntireRow.Delete End If Next cell End Sub 

这是因为你在行中前进 – 如果删除第4行,则第5行变成第4行,代码将跳转到第5行 – 实际上是第6行。

希望这是有道理的。 🙂

解决方法是使用For Next Loop – 向后步进,而不是For Each Loop。

另外 – 如果没有空白行,特殊的单元格删除行将失败。

我已更新您的代码以包含这些更改:

 Sub ProcessRemittance() 'Each variable needs a type - otherwise they're variants. Dim remitDate As Date, remitNumber As Long, myString As String, tempString As String Dim myRange As Range, cell As Range Dim StringArray As Variant Dim x As Long On Error GoTo ERROR_HANDLER With ActiveWorkbook.Worksheets("Sheet1") .Range("A1:A10").SpecialCells(xlCellTypeBlanks).EntireRow.Delete For x = 10 To 1 Step -1 myString = Left(.Cells(x, 1), 3) If myString <> "00 " Then .Cells(x, 1).EntireRow.Delete End If Next x End With On Error GoTo 0 Exit Sub ERROR_HANDLER: Select Case Err.Number Case 1004 'No cells were found (occurs if SpecialCells returns nothing). Err.Clear Resume Next Case Else MsgBox "Error " & Err.Number & vbCr & _ " (" & Err.Description & ") in procedure ProcessRemittance." Err.Clear End Select End Sub