Delete Columns based on Date Range

bujaman

Board Regular
Joined
Apr 2, 2009
Messages
56
I have a worksheet with a bunch of data and I need to delete 2 adjacent columns if their date (found in row 2) is outside of a selected range. I have it sort of working, but it is deleting every other date outside the date range. I think it has something to do with the For Each, Next coding, but I can't figure a way around it. Any help is awesome! Here is my code so far:

Code:
Sub deleteColumns()

Dim rngDates As Range
Dim startDate As Date
Dim endDate As Date

Set rngDates = Worksheets("Temp").Range("M2:EE2")
startDate = Worksheets("Start").Range("B2")
endDate = Worksheets("Start").Range("B3")

Worksheets("Temp").Activate
For Each cell In rngDates

    If cell = "" And cell.Offset(0, 1) <= startDate Or cell >= endDate Then
        cell.Resize(, 2).EntireColumn.Delete
    End If
    
Next cell

End Sub
 

Excel Facts

How can you automate Excel?
Press Alt+F11 from Windows Excel to open the Visual Basic for Applications (VBA) editor.
Should this line:
Code:
If cell = "" And cell.Offset(0, 1) <= startDate Or cell >= endDate Then
not be like this?:
Code:
If cell = "" And cell.Offset(0, 1) <= startDate Or [U]cell = "" And[/U] cell.Offset(0, 1) >= endDate Then
 
Upvote 0

Forum statistics

Threads
1,215,130
Messages
6,123,220
Members
449,091
Latest member
jeremy_bp001

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