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

前端 未结 3 1545
走了就别回头了
走了就别回头了 2020-12-20 16:32

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:



        
相关标签:
3条回答
  • 2020-12-20 16:59

    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
    
    0 讨论(0)
  • 2020-12-20 17:21

    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
    
    0 讨论(0)
  • 2020-12-20 17:22

    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
    
    0 讨论(0)
提交回复
热议问题