Delete Columns that

eponcedeleon

New Member
Joined
Aug 18, 2023
Messages
5
Office Version
  1. 365
  2. 2021
Platform
  1. Windows
I am trying to delete columns that do not have certain names in header.

Thi is my code

VBA Code:
Sub Delete_Specifc_Column()
Dim LastColumn As Long
LastColumn = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Column

  Dim rng As Range
  Set rng = ActiveSheet.UsedRange

Set rng = Range("A1:A" & LastColumn)

For Each cell In rng
abc = cell.Value
   If cell.Value2 <> "Due Date" Or cell.Value2 <> "Task " Or cell.Value2 <> "Contact" Then
      ' MOVE TO NEXT CELL
   Else
    cell.EntireColumn.Delete
   End If
Next
End Sub

Here are the column headers. I only want to keep the columns "Due Date", "Task" and "Contact"

1692332820732.png


I cant figure out why my code is not working.
 

Excel Facts

Do you hate GETPIVOTDATA?
Prevent GETPIVOTDATA. Select inside a PivotTable. In the Analyze tab of the ribbon, open the dropown next to Options and turn it off
VBA Code:
Sub Delete_Specifc_Column()
Dim LastColumn As Long, rng As Range, c%
LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
Set rng = Range([A1], Cells(1, LastColumn))
For c = rng.Count To 1 Step -1
    If rng(c) <> "Due Date" And rng(c) <> "Task " And rng(c) <> "Contact" Then _
        rng(c).EntireColumn.Delete
Next
End Sub
 
Upvote 1
If the columns to be retained are always in the same place :
VBA Code:
Sub Delete_Specifc_Column()
Union([C1:D1], [F1].Resize(, Columns.Count - 5)).EntireColumn.Delete
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,896
Messages
6,175,264
Members
452,627
Latest member
KitkatToby

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