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
 

Some videos you may like

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying

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.
 

Watch MrExcel Video

Forum statistics

Threads
1,122,819
Messages
5,598,293
Members
414,223
Latest member
Accountant2B

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