运行“ For循环”时跳过空白

时间:2019-03-13 12:55:48

标签: excel vba

你好,我编写了简单的代码来比较范围内的日期: “从单元格“ G9”开始到列末尾” 将这个范围内的日期与今天的日期进行比较,并返回将要放置在“ P”列中相应单元格的天数之差

问题是:我需要在循环时跳过空格,因此如果单元格为空白,则vba将跳过并转到下一个单元格

Sub overduedate()
    Dim LastRow  As Long, i As Long

    With Worksheets("sheet1")
        LastRow = .Cells(.Rows.Count, "G").End(xlUp).Row
        For i = 9 To LastRow
            .Range("P" & i).Value = DateDiff("d", .Range("G" & i).Value, Date)
        Next i
    End With
End Sub 

1 个答案:

答案 0 :(得分:2)

赞:

Sub overduedate()
    Dim LastRow  As Long, i As Long
    Dim cell as range

    With Worksheets("sheet1")
        LastRow = .Cells(.Rows.Count, "G").End(xlUp).Row
        For i = 9 To LastRow
            If cell.value <> vbNullString then
                .Range("P" & i).Value = DateDiff("d", .Range("G" & i).Value, Date)
            End If
        Next i
    End With
End Sub 

或者您可以使用If语句而不使用End If,如下所示:

Sub overduedate()
    Dim LastRow  As Long, i As Long
    Dim cell as range

    With Worksheets("sheet1")
        LastRow = .Cells(.Rows.Count, "G").End(xlUp).Row
        For i = 9 To LastRow
            If cell.Value <> vbNullString then .Range("P" & i).Value = DateDiff("d", .Range("G" & i).Value, Date)
        Next i
    End With
End Sub