如何在VBA中的for循环中使用If语句?

时间:2018-05-31 21:25:37

标签: vba excel-vba excel

在D栏中,我试图删除其中包含值的每一行。如果单元格为空白,则不会删除

For循环只查看D2并删除整行,因为它有一个值。循环然后停止,并且不继续。 NumRows值为9324,因为A列中有很多行。

我陷入困境,无法弄清楚如何让循环继续下去。谢谢!

Dim VarDeleteLoop as long
Dim NumRows As Long


NumRows = Worksheets("Sheet").Cells(Application.Rows.Count, "A").End(xlUp).Row


For VarDeleteLoop = 2 To NumRows

        Cells(VarDeleteLoop, 4).Select

        If Cells(VarDeleteLoop, 4).Value = "" Then
                Cells(VarDeleteLoop, 4).Select
        Else
                Cells(VarDeleteLoop, 4).Select
                Selection.EntireRow.Delete
        End If

Next VarDeleteLoop

2 个答案:

答案 0 :(得分:4)

当移除东西时,通常更好的做法是向后移动。这样,如果删除了上一行,您就不需要跟踪下一行的编号。

改为执行你的for循环:

function f(options) {
  const x = options.x;
  if (x === null || x === undefined) throw new Error('x is required option');
  ...
}

答案 1 :(得分:1)

.AutoFilter可以快速隔离非空白细胞并识别它们以进行删除。

With Worksheets("sheet").Columns("D").Cells
    If .Parent.AutoFilterMode Then .Parent.AutoFilterMode = False
    .AutoFilter field:=1, Criteria1:="<>"
    With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
        If CBool(Application.Subtotal(103, .Cells)) Then
            .SpecialCells(xlCellTypeVisible).EntireRow.Delete
        End If
    End With
    .Parent.AutoFilterMode = False
End With
相关问题