2017-04-06 19 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以任何一種方式進行測試。 –