2017-04-06 80 views
2
I have a workbook like so: 

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

我想运行一个宏,但只有当我的范围内的所有单元格都是有效日期而不是空的。VBA检查全程有效日期并非空白?

我使用的是下面:

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 

但是,这是行不通的。无论如何,宏仍然运行!如果这个列中的我的单元格是重要的数据验证列表。

请有人能告诉我我要去哪里吗?

+0

@ScottCraner感谢您的建议,但没有奏效 – user7415328

+0

你想,如果它包含一个日期运行范围内的每个小区的宏或者你只是想仅在所有单元格都是日期而不是空白时才运行一次宏? – sktneer

回答

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 
+0

我认为检查IsDate(cell.Value)就足够了,因为如果单元格为空或包含一些空白区域,IsDate也可以处理该单元格。 – sktneer

+0

@sktneer你可能是正确的。但我会允许OP以任何一种方式进行测试。 –