VBA- Check if date cells in column are between 17:00 from previous day to 17:00 current day and clear contents if they are not in between the time

Indominus

Board Regular
Joined
Jul 11, 2020
Messages
160
Office Version
  1. 2016
Platform
  1. Windows
Hi, how would I clear the cell contents which are formatted as dates in a column if the dates do not fall in between 17:00 from yesterday to 17:00 on the current day? Using VBA. Thank you in advance!
 

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
Insert this code into your workbook as module, select desired cells and run it as a Macro (Ribbon Menu > Developer > Macros)

VBA Code:
Sub clearDates()
   Dim ws As Worksheet
   Dim sel As Range
   Dim cel As Range
   Dim currDate As Date
   Dim prevDate As Date
   
   Dim curr As Date
   Dim prev As Date
   
   currDate = Date
   prevDate = currDate - 1
   curr = DateValue(currDate) + TimeValue("17:00:00")
   prev = DateValue(prevDate) + TimeValue("17:00:00")
   
   Set ws = ActiveSheet
   Set sel = Selection
   
   For Each cel In sel
      If IsDate(cel) Then
         If (cel.Value2 < prev Or cel.Value2 > curr) Then
            cel.ClearContents
         End If
      End If
   Next
   
End Sub
 
Upvote 1
Solution

Forum statistics

Threads
1,223,950
Messages
6,175,582
Members
452,653
Latest member
craigje92

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top