Delete all other columns

canyon

New Member
Joined
Jan 5, 2022
Messages
24
Office Version
  1. 2019
Platform
  1. Windows
I'm trying to write some code that deletes the unspecified columns based on the header and for one reason or another the code does not execute.

VBA Code:
wbDest.Activate

lastColumn = Cells(1, Columns.Count).End(xlToLeft).Column

    For i = 1 To lastColumn
        If Cells(1, i).Value <> "Ordered Date:" And Cells(1, i).Value <> "Ship Confirm Date" And Cells(1, i).Value <> "Order Header" And Cells(1, i).Value <> "Customer PO Number (Line)" _
        And Cells(1, i).Value <> "Ordered Item" And Cells(1, i).Value <> "Ordered Item Description" And Cells(1, i).Value <> "Requested Quantity" _
    Then Columns(i).EntireColumn.Delete Shift:=xlToLeft
    
    Next i
 

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
What do you mean by "the code does not execute"
 
Upvote 0
When deleting rows/columns in a loop, you need to work backwards, otherwise certain columns will get skipped over, i.e.
VBA Code:
    For i = lastColumn to 1 Step -1
 
Upvote 0
You can also use select case for that like
VBA Code:
wbDest.Activate

lastColumn = Cells(1, Columns.count).End(xlToLeft).Column

    For i = lastColumn To 1 Step -1
      Select Case Cells(1, i).Value
         Case "Ordered Date:", "Ship Confirm Date", "Order Header", "Customer PO Number (Line)", _
               "Ordered Item", "Ordered Item Description", "Requested Quantity"
         Case Else
            Columns(i).EntireColumn.Delete Shift:=xlToLeft
      End Select
    Next i
 
Upvote 0
Solution

Forum statistics

Threads
1,223,888
Messages
6,175,212
Members
452,618
Latest member
Tam84

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