In this post we will see how to delete all the columns in excel except some of the specified columns, we will write a vba code to perform this task and we will specify column names that don’t want to delete in the vba code itself.
Suppose we have excel data with column from A to M and we want to retain column D,F,H and J in the excel data and delete all other columns using excel vba.
Open VB editor from Developer tab in excel as shown in the figure.
Insert a module in which we will write a VBA code which will delete all the columns in excel in reverse order and keep certain column that we have specified in the VBA program.
Now double click the newly created module to open that and paste the below code in the module.
Dim currentColumn As Integer
Dim columnHeading As String
For currentColumn = ActiveSheet.UsedRange.Columns.Count To 1 Step -1
columnHeading = ActiveSheet.UsedRange.Cells(1, currentColumn).Value
‘CHECK WHETHER TO KEEP THE COLUMN
Select Case columnHeading
Case “D”, “F”, “H”, “J”
‘Delete if the cell doesn’t contain “Homer”
If InStr(1, _
ActiveSheet.UsedRange.Cells(1, currentColumn).Value, _
“Homer”, vbBinaryCompare) = 0 Then
Now run the program by pressing F5 or by pressing play button in the VB editor, this macro will iterate over the columns in reverse order, check the headers in a Select Case, and delete the columns as needed.
Hope this helped.