Set the Background Color according to the date using VBA in Microsoft Excel

 

In this article, we will create a macro to highlight data for the defined date range.
Raw data consists of day-wise details of items sold by agents.

 

ArrowMain

 

Specify the start and end date, before running the macro. The macro takes the value in cell H8 as the start date and value in H9 as the end date. Click on ‘Submit’ button to run the macro.

 

ArrowOutput

 

Data between the mentioned dates has been highlighted in yellow color.

Logic explanation

We have created a “Marking” macro to highlight the data, based on the specified date range. This macro is linked to “Submit” button.

Code explanation

StartDate = Cells(8, 8).Value
EndDate = Cells(9, 8).Value

The above code is used to specify the start date and end date.

Set Source = Range(“A1:A” & LastRow)

The above code is used to initialize the source data range.

Set Start = Source.Find(CDate(StartDate), LookAt:=xlWhole)

The above code is used to find the first occurrence of specified date.

Range(Cells(Start.Row, 1), Cells(Off.Row, 3)).Select

The above code is used to select the defined range.

Selection.Interior.Color = RGB(255, 255, 0)

The above code is used to highlight the selected range in yellow color.

 

Please follow below for the code

Option Explicit

Sub Marking()


'Declaring Variables
Dim Source As Range
Dim Start As Range, Off As Range
Dim StartDate As Date
Dim EndDate As Date
Dim LastRow As Long

'Initializing start and end date
StartDate = Cells(8, 8).Value
EndDate = Cells(9, 8).Value

'Getting the row number of the last cell
LastRow = ActiveCell.SpecialCells(xlCellTypeLastCell).Row

'Initializing the source range
Set Source = Range("A1:A" & LastRow)

'Finding the cell containing first reference of the value
Set Start = Source.Find(CDate(StartDate), LookAt:=xlWhole)
Set Off = Source.Find(CDate(EndDate), LookAt:=xlWhole)

'Selecting the range
Range(Cells(Start.Row, 1), Cells(Off.Row, 3)).Select

'Assigning Yellow color to selection
Selection.Interior.Color = RGB(255, 255, 0)

End Sub

 

If you liked this blog, share it with your friends on Facebook. Also, you can follow us on Twitter and Facebook.

We would love to hear from you, do let us know how we can improve our work and make it better for you. Write to us at info@exceltip.com



2 thoughts on “Set the Background Color according to the date using VBA in Microsoft Excel

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>