Home » excel » excel vba – vba calculate days between dates in two cells, only return a value if both cells have a date

excel vba – vba calculate days between dates in two cells, only return a value if both cells have a date

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have the below code to calculate days between dates in two cells, but it returns an error value if column X has no date. I want the code to only return a value if there is a date in column X, but I don’t know how to do that. I am new to VBA. Thanks in advance for any help you can give.

Sub CalcDays()
Dim LastRow As Long
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet
Set ws = wb.Sheets("Sheet2")

LastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

With Range("AA2:AA" & LastRow)
    [AA:AA] = [X:X-Z:Z]
End With

End Sub
How to&Answers:

You could do something like:

[AA:AA] = [if(X:X="", "", if(Z:Z="", "", X:X-Z:Z))]