Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the difference between dates in VBA

I am trying to find out the difference between the system date and the date stored in the worksheet. If the difference between them is > 30 days, the result is true, else the result is false

Dim result as boolean
Dim sDate as string
sDate = Date
if Worksheets("dates").Cells(1,1) - sDate > 30 then 'how do I do this?
     result = true
else
     result = false
end if

How do I find out the difference in days between the system date and the date stored in the worksheet? The date in the worksheet can be a past date, too.

like image 809
Ank Avatar asked Nov 22 '11 02:11

Ank


People also ask

How do you compare in VBA?

Checks if the value of the two operands are equal or not. If the values are not equal, then the condition is true. (A <> B) is True. Checks if the value of the left operand is greater than the value of the right operand.

How do I use Cdate in VBA?

Step 1: Write the subprocedure of VBA CDate as shown below. Step 2: Now we will declare 3-4 different variables of Data type Date. Let's declare the first variable as Date1 and give it the data type as Date as shown below. Step 3: Now assign any number which we want to convert it in Date format.

What does Cdate mean in VBA?

VBA CDATE is a data type conversion function that converts a data type, either text or string, to a date data type. Once we convert the value to date data type, we can play around with date stuff.

Can Excel calculate the difference between two dates?

Calculate the difference in daysType =C2-B2, and then press RETURN . Excel displays the result as the number of days between the two dates (104). Select cell D2. Excel adjusts the cell references automatically to include the correct values for each row.


2 Answers

I wonder why I rarely see people using the date functions.

You can also use this:

if DateDiff("d", date1, date2) > 30 then

in this case, date1 would be CDate(Worksheets("dates").Cells(1,1)) and date2 would be sdate (either cast with CDate or dim'd as a date as Jeff said.

"d" means we are getting the difference in days. Here are the intervals for years, months, etc. in VBA:

yyyy - Year
q - Quarter
m - Month
y - Day of year
d - Day
w - Weekday
ww - Week
h - Hour
n - Minute
s - Second
like image 52
Justin Self Avatar answered Oct 12 '22 12:10

Justin Self


Try this:

if CDate(Worksheets("dates").Cells(1,1)) - sDate > 30 then
like image 26
Jeffrey L Whitledge Avatar answered Oct 12 '22 13:10

Jeffrey L Whitledge