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

Why does 9 mean SUM in SUBTOTAL?
It is because Sum is the 9th alphabetically in Average, Count, CountA, Max, Min, Product, StDev.S, StDev.P, Sum, VAR.S, VAR.P.
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,215,094
Messages
6,123,071
Members
449,092
Latest member
ipruravindra

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