VBA to delete columns based on header value

xdriver

Board Regular
Joined
Mar 21, 2014
Messages
73
Office Version
  1. 365
Platform
  1. MacOS
I am working off of this thread mrexcel, but am having trouble with it. I am using excel for mac 2011

Two things:
1. First is that when I run this, it highlights the ".Cells(1, i).EntireColumn.Delete" and says "Runtime errorr '1004': Delete method of Range class failed."
2. Where I have "BASEMENT_SF," I would prefer it to be non specific and find all cases of "_SF" that occur in row 1, and possibly anywhere it has the case of "_SF" or "_MF", or others, each of which would be in different cells, but still in the first row.


VBA Code:
Sub DelSF()
    Dim i As Long, lc As Long
    'Assumes header is in row 1
    With Sheets("Export")
       lc = .Cells(1, Columns.Count).End(xlToLeft).Column
        For i = lc To 1 Step -1
            If InStr(.Cells(1, i), "BASEMENT_SF") > 0 Then
                .Cells(1, i).EntireColumn.Delete
            End If
        Next i
    End With
End Sub

Thank you
 

Excel Facts

Copy formula down without changing references
If you have =SUM(F2:F49) in F50; type Alt+' in F51 to copy =SUM(F2:F49) to F51, leaving the formula in edit mode. Change SUM to COUNT.
Tested to work on Mac Excel 2011:
VBA Code:
Sub DelSF()
    Dim i As Long, lc As Long
    'Assumes header is in row 1
    With Sheets("Export")
       lc = .Cells(1, Columns.Count).End(xlToLeft).Column
        For i = lc To 1 Step -1
            If InStr(1, .Cells(1, i), "BASEMENT_SF", vbTextCompare) > 0 Then
                .Columns(i).Delete
            End If
        Next i
    End With
End Sub
 
Upvote 0
I got it working but I am unsure how. My next question is what is the most efficient way I can add multiple attributes to delete? Such as "_SF", "_MF", "_CC" and a slew of others?


Thank you
 
Upvote 0

Forum statistics

Threads
1,213,489
Messages
6,113,952
Members
448,535
Latest member
alrossman

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