Please help modify code delete columns macro

jmthompson

Well-known Member
Joined
Mar 31, 2008
Messages
966
How could I change this code to find the cell = MyMonthandYear and delete all columns to the left of that column up to and including column "P"? Basically, in the range from P-last column, I want to keep the column with header that matched MyMonthandYear and all columns to the right of that column.

Code:
Sub MyColumn()
MyMonthandYear = Format(Date, "mmmm-yy")
LastColumn = Range("IV1").End(xlToLeft).Column
For i = LastColumn To 16 Step -1
If (Cells(1, i).Value) <> MyMonthandYear Then
Cells(1, i).EntireColumn.Delete
End If
Next i

End Sub
 

Excel Facts

Back into an answer in Excel
Use Data, What-If Analysis, Goal Seek to find the correct input cell value to reach a desired result

jmthompson

Well-known Member
Joined
Mar 31, 2008
Messages
966
This seems to work

Code:
Sub MyColumn()
MyMonthandYear = Format(Date, "mmmm-yy")
Dim MyMonth As Range
LastColumn = Range("IV1").End(xlToLeft).Column
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
For i = LastColumn To 16 Step -1
If (Cells(1, i).Value) = MyMonthandYear Then
Cells(1, i - 1).EntireColumn.Delete
End If
Next i
 
End Sub
 

jmthompson

Well-known Member
Joined
Mar 31, 2008
Messages
966
Oops! Ignore "Dim MyMonth as Range" Tha was leftover from a previous attempt.
 
Master Excel Bundle

Excel contains over 450 functions, with more added every year. That’s a huge number, so where should you start? Right here with this bundle.

Forum statistics

Threads
1,164,026
Messages
5,835,020
Members
430,332
Latest member
Charly_Moon

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
Top