How to check if a date cell in Excel is empty?

别来无恙 提交于 2019-11-29 13:36:33

Since only variables of type Variant can be Empty, you need a different test for Date types.

Check for zero:

If agreedDate = 0 Or completedDate = 0 Then

But a safer path would be to change the variables to type Variant and then do this test:

If IsDate(agreedDate) = False Or IsDate(completedDate) = False Then

The IsEmpty function determines indicated whether a variable has been initialized. If a cell is truly blank then it is considered uninitialized from the IsEmpty standpoint. However, declaring a variable in VBA gives it a default value. In this case the date type variables are essentially 0 or 30-Dec-1899 00:00:00 as demonstrated by the following short snippet.

Sub date_var_test()
    Dim dt As Date
    Debug.Print Format(dt, "dd-mmm-yyyy hh:mm:ss")
End Sub

If you want to 'tidy up' your code, you might also wish to allow the true boolean return of the IsEmpty function to resolve the boolean condition rather than comparing it to True.

If IsEmpty(Worksheets("Data").Cells(Counter, 7)) Or IsEmpty(Worksheets("Data").Cells(Counter, 9)) Then
    [.. do stuff]
End If

Given that False is (for all intents and purposes) zero then this will work for your date type variables.

If Not (agreedDate or completedDate) Then
    [.. do stuff]
End If

As Excel Hero pointed out, a date variable cannot be empty. In fact, a date variable is a number, so you should be able to do something like this. Also, notice that the code below uses "Value2".

Sub test()
    Dim d As Date
    d = Range("A1").Value2
    If d = 0 Then
      MsgBox "ok"
    Else
      MsgBox "not ok"
    End If
End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!