Skip to content

Excel VBA – Conditionally Format Dates Within Date Period

    Use FormatConditions.Add  FormatConditions is a property of the Range object.  Add has the following parameters.  The FormatConditions collection can only hold 3 FormatConditions.

    FormatConditions.Add(Type, Operator, Formula1, Formula2)

    To apply formatting to values within a specific date period use xlTimePeriod in the Type parameter and then use the DateOperator parameter to specify the date period – options shown in the table below.

    NameValueDescription
    xlLast7Days2Last 7 days
    xlLastMonth5Last month
    xlLastWeek4Last week
    xlNextMonth8Next month
    xlNextWeek7Next week
    xlThisMonth9This month
    xlThisWeek3This week
    xlToday0Today
    xlTomorrow6Tomorrow
    xlYesterday1Yesterday
    Sub formatlastweek()
    Dim rg As Range
    Set rg = Range("H5", Range("h5").End(xlDown))
    Dim cf As FormatCondition
    Set cf = rg.FormatConditions.Add(Type:=xlTimePeriod, DateOperator:=xlLastWeek)
    cf.Interior.Color = rgbDarkGray
    End Sub

    The code above relates to the conditional formatting displayed below.