Open In App

VBA Date and Time Functions in Excel

Last Updated: 16 Oct, 2022

A

Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Date and Time Functions are the inbuilt functions that give us the opportunity to see the date or time according to the user’s need. Suppose a user needs to see the month or the day or the year then it can be easily seen by different date functions. Similarly, for the time function, also we can manipulate it according to the need of the user. Date and Time functions are used to interconvert date and time in different formats. In this article, we will learn about the most commonly used date and time functions.  

VBA Date Functions 

There are fifteen-plus different date functions in VBA, but here we will talk about some of the most commonly used date functions. 

VBA Date Function

The Date() function returns the current date. The Date() function does not require any arguments. For example, declare a variable name date_1 of Date data type, call the Date() function, and store the return value in date_1, then print the date_1 in the console. 

Syntax of the function: Date()

date function in vba

 

VBA DateAdd Function

The DateAdd() function is used to add an interval of date/time to the respective date or time. The function will return the resulting date or time. The function takes three arguments, Interval, Number, and Date/Time. 

Syntax of the function: DateAdd(Interval, Number, Date/Time)

Interval: The first argument, represents, which part of the Date/Time, you want the interval to be added. 

Types of intervals are discussed in the following table:

Intervals Specification
“d” Day
“ww” Week
“m” Month
“q” Quarter
“yyyy” Year
“y” Day of the year
“h” Hour
“n” Minute
“s” Second

Number: The second argument represents, the number of Intervals we want to add to the Date/Time.

Date/Time: The third argument represents, the Date/Time on which the changes have to occur. 

For example, the current date is “20/11/2020”, and we want to increase the month count by 8. Then use, DateAdd(“m”, 8, “20/11/2020”), and the final output date will be “20/07/2021”

DateAdd function in VBA

 

VBA DateDiff Function

The DateDiff() function is used to get the difference between two dates, in terms of the year, month, day, hours, seconds, etc. The function will return the resulting Date/Time. The functions take three mandatory arguments, Interval, Date1, and Date2. 

Syntax of the function: DateDiff(Interval, Date1, Date2)

Interval: The first argument, represents, the part of the Date/Time, you want to see the difference. For example, in terms of the year, day, month, etc. Refer to the table in VBADateAdd() function, for the values of Interval.  

Date1: Date1 is the second argument. It tells the start date in an interval. 

Date 2: Date2 is the third argument. It tells the end date in an interval. 

For example, consider Date1 as “20/10/2020”, and Date2 as “20/12/2021”, and the difference in terms of “d”(days). The final output of the function will be 426

datediff function in vba

 

VBA DatePart Function

The DatePart() function is used to get a particular part(day, week, year) from the date. The function returns the part of date in asked format by the user. The function takes two mandatory arguments, Interval, Date. 

Syntax of the function: DatePart(Interval, Date)

Interval:  The first argument, represents, the part of the Date/Time, one wants to see. For example, “yyyy” represents the year, and tells the DatePart function to return the year of an input Date. 

Date: The second argument, which represents the date user will enter, to check a particular part of a date. 

For example, consider the Date as “10/10/2020”, and it has been asked to print the year of this particular date. So, we will use “yyyy” as the first argument. The final output is 2020

datepart function in vba

 

VBA MonthName Function

The MonthName() function returns the name of the month according to the integer value. The function takes one mandatory argument, a number. 

Syntax of the function: MonthName(number)

number: The first argument, which tells about the number of the month. 

For example, 11 is the argument of the MonthName() function, the function returns “November”

monthname function in vba

 

VBA Time Functions

There are ten-plus different time functions in VBA, but here we will talk about some of the most commonly used time functions. 

VBA Now Function

The Now() function is used to get the current date and time of the system. The function does not take any arguments. For example, declare a variable name date_2 of Date data type, call the Now() function, and store the return value in date_2, then print the date_2 in the console. 

Syntax of the function: Now()

now function in vba

 

VBA Time Function

The Time() function is used to get the current time of your system. The function does not take any arguments. For example, call the Time() function, and the system will return the current time i.e. 5:20:20 PM.

Syntax of the function: Time()

time function in vba

 

VBA Hour Function

The hour() function is used to get the hour from the time. The function takes one mandatory argument, Time. 

Syntax of the function: hour(Time)

Time: The first argument, which represents the time user will enter. 

For example, consider the time “1:08:42 PM”, and it has been asked to print the hour of this particular time. The final output will be 1

hour function in vba

 

VBA Minute Function 

The minute() function is used to get the minute from the time. The function takes one mandatory argument, Time.

Syntax of the function: minute(Time)

Time: The first argument, which represents the time user will enter.

For example, consider the time “1:08:42 PM”, and it has been asked to print the minute of this particular time. The final output will be 08

minute function in vba

 

VBA Second Function

The second() function is used to get the seconds from the time. The function takes one mandatory argument, Time.

Syntax of the function: second(Time)

Time: The first argument, which represents the time user will enter.

For example, consider the time “1:08:42 PM”, and it has been asked to print the seconds of this particular time. The final output will be 42

second function in vba

 



A

News
Improve
Discuss
Do you want to advertise with us?Click here to know more

VBA Subroutine in Excel - How to Call Sub in VBA?

article_img
When a specified action is performed on a worksheet with the help of a collection of code known as a VBA Subroutine. It also helps to read an external file, also it can open other applications from Excel. A large piece of code can be broken into small parts so that we can manage it easily. Let's learn why to use submarines: Converts large piece of codes into small parts so that the computer ignores all kind of complexities that arises because of large codesReusability of code suppose we in a program have to access the database frequently so instead of writing the code again and again we can create a function to access the databaseSubroutines are self-documenting functions which means a coder can easily say what the program does by looking into the name of the function Naming Rules of SubroutinesIt can start with a letter or an underscore but it cannot start with a number or a special character.It cannot contain any space in the name.The name of the subroutine cannot be a keyword like Private, Sub, End, etc. Syntax Private Sub function_name( ByVal arg1 As String, ByVal arg2 As String) End Sub Syntax Explanation Code Action "Private Sub function_name(...)"Private is the keyword whic
Read More

How to Get a List of User Defined Functions in Excel VBA?

Microsoft provides many built-in functions to speed up your work in Excel. However, you can technically create functions using VBA coding called "user-defined functions" (UDFs). Also known as a "user-defined function" in Excel VBA. A formula that can be accessed from a worksheet using a piece of code is called a UDF. Simply put, formulas that are not built-in but available in Excel are called "user-defined functions". Using VBA, you can create user-defined functions (also called user-defined functions) that can be used in worksheets like regular functions. These are useful when existing Excel functionality is not sufficient. In such cases, you can create your own custom user-defined functions (UDFs) to meet your specific needs. This tutorial covers all about creating and using user-defined functions in VBA. How to create User defined functions? UDF is part of a module, but not part of a regular subroutine in VBA. In VBA they are called function procedures. Just like you start your macro coding with the word SUB, you should start it with the word "Function". A sub-procedure has a beginning and an end. Similarly, a Function procedure has a Start and an End. Create SUM function in Exc
Read More

Excel VBA | sum() functions

article_img
Visual Basic for Applications (VBA) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft. With Excel VBA one can automate many tasks in excel and all other office software. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its various functions. Let's see Sum functions in Excel. SUM: Adds all the numbers in a range of cells. Syntax: =SUM(number1, number2…) Here, number 1: This is the first number in your cell to add. You can specify it upto 255 numbers. number 2: This is an Optional field. You can add upto 255 numbers. Example: Output: SUMIF: Allows to add the cells depending upon the criteria you’ve provided. Syntax: =SUMIF(range, criteria, sum_range) range: It is the range of cells which you want to evaluate. The cells in range can be numbers, names or arrays or any other reference that contains numbers. criteria: It should be in the form of a number or any expression which defines which all cells to be added. For instance, “mango”, C6, “<35” sum_range: This field is Optional. If this is not mentioned, Excel will add only those cells on which criteria is appl
Read More

Excel VBA | Average() Functions

article_img
VBA (Visual Basic for Applications) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft. With Excel VBA, one can automate many tasks in excel and all other office softwares. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its various functions. Let's see Average functions in Excel. AVERAGE It returns the arithmetic mean of all of its arguments. Syntax: =AVERAGE(number1, number2, …) Here, number 1: This is the first number in your cell. You can specify it upto 255 numbers. number 2: This is an Optional field. You can specify it upto 255 numbers. Example: Output: AVERAGEIF: It calculates the average of only those values which meet a certain criteria. Syntax: =AVERAGEIF(range, criteria, average_range) range: It is the range of cells to be evaluated. The cells in range can be numbers, names, arrays or any other reference that contains numbers. Blank and text values are not considered. criteria: It should be in the form of a number or any expression which defines which all cells to be averaged. For instance, “mango”, C6, “<35” average_range: [Optional] If this
Read More

Excel VBA | count() functions

article_img
Visual Basic for Applications (VBA) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft. With Excel VBA one can automate many tasks in excel and all other office software. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its various functions. Let’s see Count() functions in Excel. COUNT: It allows to count the number of cells that contain numbers in a range. One can use the COUNT function to calculate the total number of entries in an array of numbers. Syntax:=COUNT(value1, value2…) value1: The very first item required to count numbers. value2: It can be specified upto 255 other entries which you want to count. Note: -> Only those arguments are counted that are numbers or text enclosed between quotation marks, as, “2”. -> Arguments like logical values and text representation of numbers that are typed directly are counted. -> Any values that cannot be translated to numbers are ignored. Example: Output: COUNTA: This counts only those range of cells which are not empty. Syntax:=COUNTA(value1, value2…) value1: It is the first argument to be counted. value2: All addi
Read More

Variables and Data Types in VBA Excel

article_img
In a computer system, variables and data types are almost used in every program to store and represent data. Similarly, Excel VBA also has variables and data types to store and represent data and its type. In this article, we will learn about VBA variables, their scope, data types, and much more. VBA Variables VBA(Visual Basic for Application) variables are similar to other programming languages variables, they act as a container that is used to store data(integer, string, floats, etc). We can use the variables in the code at multiple places and executer the programs. Defining Variables In VBA VBA gives permission to define variables in two ways: Implicitly - In VBA, we can implicitly declare variables using the assignment(=) operator. All the variables that are implicitly declared in VBA are of type "Variant". The variant type variables required more memory space than usual variables. Example: label="gfg"Explicitly - Explicitly we can declare variables using "Dim" keyword. Explicit variable also reduces the naming conflicts and spelling mistakes. Example: Num as password Syntax For VBA Variables // macro definition Sub VBA_Variable_Example () Dim <name> End Sub VBA V
Read More

Function and Sub in Excel VBA

article_img
In Visual Basic, the functions and sub-procedures play similar roles but have different or unique characteristics. However, both perform a programmed task. They utilize a set or group of commands to deliver the required results. The key difference between the sub and the functions is that a sub-procedure generally does not return a result whereas functions tend to return a result. Hence if there is a need for having a value post execution of tasks, then place the VBA code under a function or otherwise place the code under a sub-procedure. In Excel, there is the availability of large numbers of VBA functions that could be utilized in the development of new VBA codes. Such functions are referred to as Built-in functions. With the increase in the size of a VBA program, both Functions and Sub-procedures play a crucial role in the management and performance of VBA code. Functions in VBA A function in VBA can be defined as a procedure that executes a piece of code or instructions and post-execution, it returns the value of the tasks performed. A function is hence invoked using a variable. Functions are directly called in the spreadsheets by using excel based formulas. An excel VBA functi
Read More

How to Declare and Initialize String Array in Excel VBA?

article_img
A string array is an array where we can store only string values in the array, with the help of a string array, we can store more than one string value. We can declare the string array in many ways like declaring a static string array, declaring a variant size array of string using the Array function, and a string array using the split function which we will discuss in this article Declaring a Static String Array A static Array is an array whose size is fixed and it can be declared in two ways one is declared implicitly and another one is explicit. The following code is to declare a string array implicitly. The following code is to declare a string array explicitly. Declaring a Variant Size Array of String using Array Function In the following code an array is declared with variant size and string values are initialized using the array function: If we want to access the strings in the array then we have to write, Declaring a String Array using Split Function The following code is to declare an array without any fixed size and a split function is used to assign the string values. If we want to access the strings in the array then we have to write, By default, the lower bound
Read More

How to Insert and Run VBA Code in Excel?

article_img
In Excel VBA stands for (Visual Basic for Application Code) where we can automate our task with help of codes and codes that will manipulate(like inserting, creating, or deleting a row, column, or graph) the data in a worksheet or workbook. With the help of VBA, we can also automate the task in excel to perform all these tasks we need to insert and run the VBA code properly which we will discuss in this article. Steps to Insert and Run VBA Code in Excel To use the VBA code properly in Excel we need to change the default macro security settings of excel for that we need to follow further steps Step 1: Click on the "File" menu at the left top of the excel tab. Step 2: Select "Options" to get the "Excel Options" window. Step 3: Select "Customized Ribbon" in the "Excel Options" Window and then select the "Developer" check box in the "Main Tabs". Step 4: Then return to the main Excel window to select the "Developer" ribbon and then click on "Macro Security" in the "Code" group. Step 5: Click on "Macro Settings" to select "Disable all macros except digitally signed macros". Now, to insert and run the VBA in Excel so that we can write codes we need to follow further steps: Ste
Read More

How to Find the Last Used Row and Column in Excel VBA?

article_img
We use Range.SpecialCells() method in the below VBA Code to find and return details of last used row, column, and cell in a worksheet. Sample Data: Sample Data Syntax: expression.SpecialCells (Type, Value) Eg: To return the last used cell address in an activesheet. ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Address VBA Code: Declaring Variables: VariableData TypeCommentsLastRowLongFind and store last used rowLastColLongstore last used columnLastCellStringstore last used cell address'Variable Declaration Dim LastRow As Long, LastCol As Long, LastCell As String Use SpecialCells function to find last used row/column/cell 'Find Last Used Row LastRow = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Row 'Find Last Used Column LastCol = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Column 'Find Last Used Cell LastCell = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Address Concatenate all three variables (LastRow/LastCol/LastCell), add a new line between variables use Chr(10). Show the final output in an Excel Message box. 'Display the last used row/column/cell MsgBox "Last Used Row : " & LastRow & Chr(10) & "Last Used Column :
Read More
three90RightbarBannerImg