VBA DAY FUNCTION

What is VBA Day Function?

In VBA, the Day function is used to extract the day component from a specified date. It takes a date as an argument and returns an integer representing the day of the month. See the example below:

Excel VBA Day Function 1

Define a sub-procedure using the VBA Day function two digits and extracting the “DD” component from the date given. The result is printed in the Immediate tab, as shown.The date format is “MM/DD/YYYY.”

Excel VBA Day Function 1-1
Key Takeaways
  • The Day function in VBA is used to extract the day component from a date.
  • It takes a date as an argument and returns an integer representing the day of the month.
  • The extracted day does not include the time component.
  • It cannot handle invalid dates, so it’s essential to validate dates before using the function.
  • When dealing with time components, consider using the DateValue function to remove the time portion before applying the Day function.

Syntax

The syntax to use the VBA Day function is as shown.

Day(date)

where,

  • date: The variable holding the date value.

How to Use VBA Day Function?

You can learn how to utilize the VBA Day function by going through the example below.

Step 1: In the Excel Workbook, go to the “Developer” section in the Excel toolbar.

How to use VBA Day function 1

Under “Developer,” select “Visual Basic” to open the VBA Editor.

How to use VBA Day function 1-1

In the toolbar of the VBA Editor, select “Insert,” then go to “Module” to open a new module to code in.

How to use VBA Day function 1-2

Step 2: Create a subroutine to display the current day of the week.

How to use VBA Day function 1-3

Step 3: Initialize a Date variable to store the Date value.

How to use VBA Day function 1-4

Step 4: Assign today’s date to the variable declared earlier.

How to use VBA Day function 1-5

Step 5: Initialize an integer variable to store the “day” component of the date value.

How to use VBA Day function 1-6

Step 6: Call the VBA Day function on the date value and store it in an integer variable.

How to use VBA Day function 1-7

Step 7: Print the day of the week. By formatting the date value using the VBA Format function using the “DDDD” format. It will print the day of the week.

How to use VBA Day function 1-8

Step 8: Using the MsgBox function, print all three formats.

How to use VBA Day function 1-9

Code:

Sub AnotherExample()

    Dim currentDate As Date

    currentDate = Date

    Dim dayOfMonth As Integer

    dayOfMonth = day(currentDate)

    MsgBox “Today is ” & Format(currentDate, “DDDD”)

    MsgBox “Today is the ” & dayOfMonth & “th day of the month.”

End Sub

Step 9: Click “F5” or the “Run” icon on the activity bar in the Excel VBA Module to run the program. It prints a Message Box with the different date formats in excel.

How to use VBA Day function 1-10
How to use VBA Day function 1-11

Now that you know how to use the Day function in Excel VBA, you can go through more examples below.

Examples

Learn how to use VBA Day function for various purposes.

Example #1

Using the VBA Day function’s two digits result, you can find out whether the day is an even number or an odd number. Take an input date, then find the day number, and check if it is divisible by 2 using the VBA Mod function.

Step 1: Create a subroutine to find whether the given day is an odd day or an even day.

VBA Day Function - Example 1

Step 2: Define a Date variable to store the date value from the user.

VBA Day Function - Example 1-1

Step 3: Get the date from the user and store it in the date variable defined above.

VBA Day Function - Example 1-2

Step 4: Use an If-Else condition to check if the given date is valid or not. If it isn’t valid, declare an error Message box and Exit the sub so that the rest of the code doesn’t get executed.

VBA Day Function - Example 1-3

Step 5: Define an integer variable to store the day component from the Date value.

VBA Day Function - Example 1-4

Step 6: Call the VBA Date function on the date from the user and store the result from the VBA Day function into the integer variable.

VBA Day Function - Example 1-5

Step 7: Using an If-conditional statement, check whether the day component is divisible by 2. If so, create a Message Box telling the user that the day is even.

VBA Day Function - Example 1-6

Step 8: Define an Else-conditional statement to check whether it is an odd day. If a number is not divisible by 2, it is an odd number.

VBA Day Function - Example 1-7

Code:

Sub ActionBasedOnDayFunction()

    Dim inputDate As Date

    inputDate = InputBox(“Enter a date (mm/dd/yyyy):”, “Date Input”)

    If Not IsDate(inputDate) Then

        MsgBox “Invalid date entered. Please try again.”

        Exit Sub

    End If

    Dim dayOfMonth As Integer

    dayOfMonth = day(inputDate)

    If dayOfMonth Mod 2 = 0 Then

        MsgBox “The day is even.”

    Else

        MsgBox “The day is odd.”

    End If

End Sub

Step 10: Run the above subroutine by clicking on the green arrow button on the VBA Toolbar.

VBA Day Function - Example 1-8
VBA Day Function - Example 1-9

From this, you can tell the user that the date they’ve input in is an even day.

Example #2

Suppose you have a table containing dates. You want to find the day number along with the day of the week the date is in. You can use the VBA Day and VBA Format functions to do so. Follow the steps below.

VBA Day Function - Example 2

Step 1: Define the subroutine to find the day numbers the dates have and store them in adjacent columns.

VBA Day Function - Example 2-1

Step 2: Define a range variable to store the size of the table.

VBA Day Function - Example 2-2

Step 3: Set the range of the table where this subroutine will work.

VBA Day Function - Example 2-3

Step 4: Define a for-loop running through the table and go through each cell in the range.

VBA Day Function - Example 2-4

Step 5: Call the VBA Day function to find the day number and store it in the adjacent column or the second column using the Cells function.

VBA Day Function - Example 2-5

Step 6: In the third column, print the day of the week using the VBA Format function set as “dddd” to print the weekday of the date given in the table.

VBA Day Function - Example 2-6

Step 7: Continue the FOR-loop.

VBA Day Function - Example 2-7

Code:

Sub FindAllDays()

    Dim rng As Range

    Set rng = Worksheets(“Sheet5”).Range(“A2:A7”)

    For Each i In rng

        Cells(i.Row, 2).value = day(i.value)

        Cells(i.Row, 3).value = Format(Cells(i.Row, 1).value, “dddd”)

    Next i

End Sub

Step 8: Click the green arrow button when you want to run the subroutine. Then go to “Sheet5” to see your results.

VBA Day Function - Example 2-8

Example #3

Suppose you want to know whether the current day is a prime number or not. You can extract the day component using the VBA Day function and check whether it is a prime number.

By dividing the number 2 by the square root of the number, you can find out if it’s a prime number or not. If none of the numbers from 2 to the square root of the number are divisible, then it is a prime number; otherwise, it is a composite number.

Step 1: Define a sub-procedure to check if a given day is a prime number or not.

VBA Day Function - Example 3

Step 2: Find the day component of today’s date and store it in an Integer variable.

VBA Day Function - Example 3-1

Step 3: Declare a Boolean variable as an indicator to check whether the given number is a prime number or not.

VBA Day Function - Example 3-2

Step 4: Check if the day is less than or equal to 1. If so, set the Boolean variable as False.

VBA Day Function - Example 3-3

Step 5: Define an Else condition block if the day is greater than 1.

VBA Day Function - Example 3-4

Step 6: Run a FOR-loop ranging from the number 2 to the square root of the number.

VBA Day Function - Example 3-5

Step 7: If the given number is divisible by any number from the range, set the Boolean variable as False.

VBA Day Function - Example 3-6

Step 8: End the If condition in the loop and exit the sub-procedure.

VBA Day Function - Example 3-7

Step 9: Continue the for-loop. After the loop, end the If-Else condition from Step 4.

VBA Day Function - Example 3-8

Step 10: Declare another If-condition to check if the Boolean variable is true.

VBA Day Function - Example 3-9

Print a Message Box function noting the day and that it is a prime number.

Step 11: Define an Else condition if the Boolean variable is set as False.

VBA Day Function - Example 3-10

Code:

Sub CheckPrimeDay()

    Dim currentDay As Integer

    currentDay = day(Date)

    Dim isPrime As Boolean

    isPrime = True

    If currentDay <= 1 Then

        isPrime = False

    Else

        Dim i As Integer

        For i = 2 To Sqr(currentDay)

            If currentDay Mod i = 0 Then

                isPrime = False

                Exit For

            End If

        Next i

    End If

    If isPrime Then

        MsgBox “The day of the month (” & currentDay & “) is a prime number!”

    Else

        MsgBox “The day of the month (” & currentDay & “) is not a prime number.”

    End If

End Sub

Step 12: Run the above subroutine to see if the current day is a prime number or not.

VBA Day Function - Example 3-11

The current day is not a prime number.

Important Things To Note

  • If dealing with time components, consider using DateValue to remove the time portion before applying the Day function.
  • Store the result of the Day function in variables of Integer type since it returns an integer representing the day.
  • Be aware that the Day function operates based on the system’s local time. Account for any timezone differences if your application involves multiple time zones.
  • The Day function extracts the day of the month, not the day of the week. For the day of the week, use the Weekday function.
  • The Day function is meant for date values, not time-only.
  • If the goal is to display a formatted date, consider using string formatting functions or custom date formatting instead of relying solely on the Day function.

Frequently Asked Questions (FAQs)

1) Can I use the Day function with a date stored in a variable?

Yes, you can use the Day function with a date stored in a variable by passing the variable as an argument to the Day function.

For example,
dayOfMonth = Day(myDate)

2) Can the Day function in VBA handle invalid dates?

No, the Day function in VBA does not handle invalid dates. If you pass an invalid date to the Day function, it may result in a runtime error. Validate dates before using the Day function to avoid errors.

3) Can I use the Day function in VBA with a cell reference in Excel?

Yes, you can use the Day function in VBA with a cell reference in Excel.
For example
dayOfMonth = Day(Range(“A1”).Value)

4) How do I handle time components when using the Day function in VBA?

The Day function in VBA extracts the day component from a date, excluding the time. To handle time components, use the DateValue function to remove the time. dayOfMonth = Day(DateValue(myDateTime))

This has been a Guide to VBA Day Function. Here we explain how to use VBA Day function using syntax along with examples & downloadable excel template. You can learn more from the following articles –

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *