在Excel中使用Countif删除行

从我在countif函数的其他相关问题中看到的,我不明白为什么我的代码不工作。

我有一个字段,我已经确定了要删除的行以包含值“GO AWAY”的行。 以下是我用来使它们消失的代码。 DF是我当前的工作表,由“Set DF = CWB.Worksheets(”Delete“)”和“Set CWB = ThisWorkbook”定义。

Dim iVal As Integer Dim LastRow2 As Long Dim ii As Integer Do While (iVal > 0) LastRow2 = DF.Cells(DF.Rows.Count, 1).End(xlUp).Row iVal = DF.Application.WorksheetFunction.CountIf(DF.Range("d:d"), "GO AWAY") For ii = 2 To LastRow2 If DF.Cells(ii, 4).Value = "GO AWAY" Then Rows(ii).EntireRow.Select DF.Cells.EntireRow.Select 'Caution to testers. This line and the next will delete the entire worksheet. Selection.Delete Shift:=xlUp 'Caution to testers. This line and the previous will delete the entire worksheet. End If Next ii Loop 

如果我在随机单元格中使用公式:

 =CountIf(D:D, "GO AWAY") 

返回128。

@DavidCampbell因为你的ivalvariables没有定义,所以在某些情况下默认为null或者零。 这满足了你结束Do While (ival > 0) 。 由于ival小于0,它就结束了整个Do循环。

更简单的代码来删除行:

  LastRow2 = DF.Cells(DF.Rows.Count, 1).End(xlUp).Row For ii = LastRow2 To 2 Step -1 If DF.Cells(ii, 4).Value = "GO AWAY" Then Rows(ii).EntireRow.Delete xlShiftUp End If Next ii