删除列标题中的所有列基于错误?

我使用索引匹配或hlookup很多,以确保我只得到我想要的某个文件的列。 无论我无法匹配,我需要删除。 什么是最有效的VBA脚本来删除“#N / A”的所有列标题?

使用Range.SpecialCells方法和xlCellTypeFormulas的xlCellType,并为XlSpecialCellsValue常量指定xlErrors

 Sub del_err_cols() With Worksheets("Sheet1") On Error Resume Next With .Rows(1).SpecialCells(xlCellTypeFormulas, xlErrors) .Cells.EntireColumn.Delete End With On Error GoTo 0 End With End Sub 

我觉得@Jeeped解决scheme更好,但是因为你在这里发布代码是我的build议:

 Sub del_err_colsG() Dim lastCol As Long, i As Integer lastCol = Cells(1, Columns.Count).End(xlToLeft).Column For i = lastCol To 1 Step -1 If IsError(Cells(1, i).Value) Then Columns(i).Delete Next End Sub