VBA检查整个范围是否有效并且不是空白?

时间:2017-04-06 18:56:07

标签: excel vba

I have a workbook like so:

Dates
01/02/2017
01/03/2017
BLANK
01/02/2017

我正在尝试运行一个宏,但前提是我的范围内的所有单元格都是有效日期而非空。

我正在使用以下内容:

Dim cell As Range

    'With my workbook, lets check the data
    With wb.Worksheets(1)
    Lastrow = .Cells(.Rows.count, "G").End(xlUp).Row

    'Data Check: Are all dates valid?
    For Each cell In Range("E9:E" & Lastrow)
    If IsDate(cell.Value) And Not IsEmpty(cell.Value) Then
    Continue
    Else
    Exit Sub

    End If
    Next
    End With

但这不起作用。无论如何,宏仍然运行!如果重要,我在此栏中的单元格是数据验证列表。

请有人告诉我我哪里出错了吗?

1 个答案:

答案 0 :(得分:2)

稍微颠倒逻辑:

    Dim cell As Range

    'With my workbook, lets check the data
    With wb.Worksheets(1)
        Lastrow = .Cells(.Rows.Count, "G").End(xlUp).Row

        'Data Check: Are all dates valid?
        For Each cell In Range("E9:E" & Lastrow)
            If Not IsDate(cell.Value) Or Trim(cell.Value) = "" Then
                Exit Sub
            End If
        Next
        ' the rest of your code.
        ' it will not get here if there are any blanks in or non dates in the range.

    End With