Excel VBA基于多个表格上的多个标题删除列

下面的代码是否可以修改为循环遍历工作簿中的所有工作表,并根据标题删除多个列?

例如:“状态”,“状态名称”,“状态进程”等)? 然后循环遍历wkbk中的所有表单进行相同的检查?

Sub remove_columns() For i = ActiveSheet.Columns.Count To 1 Step -1 If InStr(1, Cells(1, i), "Status") Then Columns(i).EntireColumn.Delete Next i End Sub 

 dim a as long, w as long, vDELCOLs as variant, vCOLNDX as variant vdelcols = array("status","Status Name","Status Processes") with thisworkbook for w=1 to .worksheets.count with worksheets(w) for a=lbound(vdelcols) to ubound(vdelcols) vcolndx=application.match(vdelcols(a), .rows(1), 0) if not iserror(vcolndx) then .columns(vcolndx).entirecolumn.delete end if next a end with next w end with 

显然,与存在的列相比,删除的列要less。 查找要删除的列的匹配项,而不是将每一列与删除列表进行比较。

这看起来(不区分大小写)列1中的列名称。

我会像下面一样去

 Sub Main() Dim sh As Worksheet Dim i as Long For Each sh In ThisWorkbook.Sheets With sh.UsedRange For i = .columns.Count To 1 Step -1 If InStr(1, LCase(.columns(i).cells(1)), "status") Then .columns(i).EntireColumn.Delete Next End With Next End Sub 

您需要正确引用表单,使用方便且可以使用LCase()来避免区分大小写:

 Sub remove_columns() Dim wS As WorkSheet For Each wS in ThisWorkbook.Worksheets With wS For i = .Columns.Count To 1 Step -1 If InStr(1, LCase(.Cells(1, i)), LCase("Status")) Then _ .Columns(i).EntireColumn.Delete Next i End With 'wS Next wS End Sub