You say that you want to delete any column with the heading “Percentage of marginal error”, so try to make this dynamic rather than name the columns directly.
Sub deleteCol() On Error Resume Next Dim wbCurrent As Workbook Dim wsCurrent As Worksheet Dim nLastCol, i As Integer Set wbCurrent = ActiveWorkbook Set wsCurrent = wbCurrent.ActiveSheet 'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column 'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error" For i = nLastCol To 1 Step -1 If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft End If Next i End Sub
You don’t need to worry about where you insert or import data, as long as the column headers are on the first row.
EDIT: And if your headings are not on the first line, this will be a very simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) change the value "1" in Cells(1, i) to any line that contains your headers.
EDIT 2: Changed the For section of the code to account for completely empty columns.
source share