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

流过昼夜 提交于 2019-12-18 07:45:09

问题


If feels like this should be really easy but I dont get it to work without retrieving the value of the cell again.

To start with, I have 2 date cells:

Dim agreedDate As Date
Dim completedDate As Date

THIS WORKS .. (but looks messy)

agreedDate = Worksheets("Data").Cells(Counter, 7).Value
completedDate = Worksheets("Data").Cells(Counter, 9).Value

If (IsEmpty(Worksheets("Data").Cells(Counter, 7).Value) = True) Or (IsEmpty(Worksheets("Data").Cells(Counter, 9).Value) = True) Then

[.. do stuff]
End If

THIS DOES NOT WORK - WHY NOT?!

agreedDate = Worksheets("Data").Cells(Counter, 7).Value
completedDate = Worksheets("Data").Cells(Counter, 9).Value

If (IsEmpty(agreedDate) = True) Or IsEmpty(completedDate) = True) Then

[.. do stuff]
End If

Is there a way to write the if statement in a clean and easy way?


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/33421574/how-to-check-if-a-date-cell-in-excel-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!