VBA Datediff : How to Find the “Difference” between Two Dates
Visual Basic for Applications (VBA) is integrated into the programs that come with the Microsoft Office suite, like Microsoft Word and Microsoft Excel. VBA lets you write macros (short, simple programs), which can be used to automate a task you perform repetitively. For example, in Excel you can write a macro that lets you copy the data found in a range of cells from one column and paste it in another column.
You can see how useful this is – especially if you use Excel for office work!Using Visual Basic for Applications requires a certain familiarity with the Visual Basic language. Visual Basic was developed by Microsoft to make it easy for developers to make Windows-friendly applications. If you’re unfamiliar with Visual Basic for Applications, you should consider signing up for an introductory VBA course with us. We’ll go over everything you need to know (from the basics to the advanced stuff) – you’ll be writing your own macros in no time. Before we proceed, you may want to go through this quick primer on VBA, to brush up the basics.
The DateDiff Function Syntax
In this tutorial, we’re going to give you a detailed, easy to understand overview of the DateDiff function in VBA. We’ll also teach you how to write your own macros from the basics. Even if you’re unfamiliar with the process, you should be able to create a functioning macro if you follow the steps outlined in this tutorial to the letter.
The DateDiff function in VBA can be used to find out the time interval between two distinct specified time periods. The syntax for the DateDiff function is:
DateDiff (interval, date1, date2, [firstdayofweek], [firstweekofyear])
You always have to specify the interval, date1 and date2 parameters. You don’t need to specify the firstdayofweek and firstweekofyear parameters. You can change the interval parameter to day, weekday, week, hour, second or year (among other values). The date1 and date2 will be starting date and the ending date of your two periods- and the interval you specify will be how you receive your result. For example, if you wanted to find out the difference between two dates in number of days, you will have to use the “days” interval. If you wanted to find out the difference between two dates in number weeks, you will have to use the “week” time interval. If you don’t specify the firstdayofweek parameter, the first day of the week will be set as Sunday. If you don’t specify the firstweekofyear parameter, the first week of the year will be set as the week which contains Jan 1.
Creating a Command Button
Before we show you the code to write the DateDiff function, you should insert a command button in your Excel spreadsheet. What is a command button and why do we need one? A command button, when clicked, runs the code it was linked to. You can use command buttons to start the execution of a macro and to get results. An example of a command button would be the “=” button found on the calculator built into Windows. In our case, we will link the command button to the DateDiff function.
First, you should enable the developer tab in Excel. This tab is disabled by default. The developer lets you create macros and add features and designs to your spreadsheet. To enable the tab, right click on the ribbon at the top and choose the “Customize the Ribbon…” option in the drop down menu. Here, you should select the “Developer Tab” option and click on ok, like in the screenshot below. You can also look this up in our 24-Hour VBA trainer course.
A new tab called Developer will now be available next to the View tab at the top. The Developer tab has the command button we’re after. Find the Insert Option and choose the “Command Button” under the Active X controls sub-menu. The Design Mode button at the top will become highlighted and your pointer will turn into a black cross. Click on any cell in the spreadsheet to spawn a command button, like in the screenshot given below:
You can drag and drop the command button anywhere in the spreadsheet. The Caption that appears on the command button is “CommandButton 1” by default. You can change the name of the command button by right clicking on it and choosing properties. A large list of properties will pop up to the left. We recommend you don’t change anything here (especially if you’re new to VBA), except the Caption label. Renaming the Caption label will change the visiblename of your command button to something else. For example, in our image we’ve change the visible caption of the Command Button to “Find Date”:
Now, we need to write code for our DateDiff function and link it to this command button. This way, when we click on “Find Date”, the DateDiff function will return a value. Right click on the command button and choose the “View Code” option. This will open up the Microsoft Visual Basic for Applications screen. This is where we write the code. It should look something like this:
We will write the code for the DateDiff function between the Private Sub CommandButton1_Click() and End Sub statements. The CommandButton1_Click() line of code tells VBA to execute code found after it when a user clicks on the command button. You can learn more about how to create your own macros and command buttons in this VBA course.
Using DateDiff Function to Find Difference between Two Dates in Days
Now, finally, we can write the code for the DateDiff function. First, let’s create a DateDiff function that lets us find out the difference between two time periods in number of days. The syntax for the DateDiff function, as we mentioned above, is:
DateDiff (interval, date1, date2, [firstdayofweek], [firstweekofyear])
First, we need to initialize three different variables to hold the values of the result (in number of days) and the two time periods: date1 and date2. If you’ve studied other languages before (like C or Java), you know why we need to declare these variables. If you’re unfamiliar with programming, you can also just sign up for a basic C programming course with us.
The code to declare variables would be as follows:
Dim dateone As Date, datetwo as Date, days As Integer
Here, we have declared dateone and datetwo as “Date” variables. They will hold data in a date format (“ Month Day, Year”). Days will hold data as an “Integer” (number).
Next, we need to assign values to thedateone and datetwo variables. These will be our two time periods:
dateone = DateValue(“Mar 10, 2014”) datetwo = DateValue(“Mar 15, 2014”)
Then, we write the DateDiff function. We use the “days” variable for this purpose:
days = DateDiff (“d”, dateone, datetwo)
Here, the “d” tells Visual Basic to use the “day” time interval.
Finally, we need to display the result. For this, we use a message box. Just type a single line of code at the end:
The complete program is as follows :
Private Sub CommandButton1_Click() Dim dateone As Date, datetwo as Date, days As Integer dateone = DateValue(“Mar 10, 2014”) datetwo = DateValue(“Mar 15, 2014”) days = DateDiff (“d”, dateone, datetwo) MsgBox days End Sub
You can copy paste the entire code, but we recommend you type it on your own to get a feel for VB. Once you’re done typing, alt tab to your Excel Spreadsheet. The Design Mode will be active- click on the Design Mode button (in the developer tab) to deactivate it. Finally, click on the command button. A message box with the difference in dates should pop up. You can change the values of the dateone and datetwo variables to get different results. You can also try out some of the examples in this VBA course for Excel.
Using DateDiff Function to Find Difference between Two Dates in Weeks
You can use the DateDiff function to find difference between two specified dates in number of weeks, instead of number of days. The code is similar- you just have to replace the “d” (interval) parameter with “ww”. Just modify the program we wrote earlier, like this:
Private Sub CommandButton1_Click() Dim dateone As Date, datetwo As Date, days As Integer dateone = DateValue("Mar 10, 2014") datetwo = DateValue("Mar 15, 2014") days = DateDiff("ww", dateone, datetwo) MsgBox days End Sub
Now try clicking on the command button (remember to disable design mode). You will get “0” as the result. Why did that happen?
In this case, the difference between the two dates was 0 in number of weeks. If you changed the value of dateone or datetwo be a month or two, you will get a different result. Try experimenting for yourself and see. You can also change the time interval to second (s), minute (n), hour (h), day of year (y) or month (y). For a list, select the DateDiff function in VBA with your mouse (highlight it) and press F1. You can try specifying the firstdayofweek and firstweekofyear parameters as well.
The DateDiff function is one of the simplest and most useful functions in VBA. Feel free to experiment with it. Once you’re ready to step it up a notch, go stretch yourself with our Advanced VBA course.
Top courses in Excel VBA
Excel VBA students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.