下面的代码是否可以修改为1循环遍历工作簿中的所有工作表,2根据其标题删除多个列?
示例:"状态","状态名称","状态流程"等等。)? 然后循环遍历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
答案 0 :(得分:3)
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
显然,要删除的列比存在的列少。查找要删除的列的匹配项,而不是将每列与删除列表进行比较。
这对于第1行中的列名称(不区分大小写)。
答案 1 :(得分:2)
我会像以下那样
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
答案 2 :(得分:1)
您需要使用With
轻松引用该表格,并且可以使用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