请避免由于未遵循正确的过帐格式而引起的任何错误。这是我的第一篇文章
我在row 1
中有一个标题。我想选择多个列标题,然后删除这些列。我还希望代码在指定的标题不存在的情况下也不会中断(即,如果要搜索的标题不存在,则循环继续)。
我有可以找到指定标题并删除该列的代码。但是,我不想为每个要删除的标题(大约20个标题)执行此代码。我也不知道如何制作,这样就不会出现标题不中断的情况。这将是我每月执行的操作,很可能所有标题都将始终相同,但是我不能保证。我下载了.cs
v文件并使用该文件。
代码中的MsgBox
来自我在网上找到的示例。如果找不到标题,我实际上并不需要消息框。我只希望它跳过找不到的标题,然后继续搜索其他标题。
Find a column header and delete that column
Dim rngHeadings As Range
Set rngHeadings = Range("A1", Range("A1").End(xlToRight)).Find("Category")
If rngHeadings Is Nothing Then
MsgBox "Can't find that"
Exit Sub
End If
rngHeadings.EntireColumn.Select
Selection.Delete
所以“ Category
”是标题之一。其他一些是“ AirDur
,” RefNbr
“等(我可以填写其余部分)。
答案 0 :(得分:2)
Dim rngHeadings As Range, f As Range
Set rngHeadings = ActiveSheet.Rows(1)
For Each h in Array("Category","AirDur")
Set f = rngHeadings.Find(What:=h, lookat:=xlWhole)
If Not f Is Nothing Then f.EntireColumn.delete
Next h
答案 1 :(得分:1)
这是我的答案,请查看评论以了解详细信息。
Sub delColumns()
Dim ws As Worksheet: Set ws = ThisWorkbook.ActiveSheet 'better use Thisworkbook.Sheets("SheetName") / or ActiveWorkbook / or specific workbook
Dim lCol As Long: lCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column 'Get the last column
Dim R As Long, C As Long
Dim arrHeadingsToDelete() As String
arrHeadingsToDelete = Split("Category,AirDur,RefNbr", ",") 'Add more as needed
For C = lCol To 1 Step -1 'Loop from last column to first
For R = LBound(arrHeadingsToDelete) To UBound(arrHeadingsToDelete) 'Loop through each of the headings in the above array
If ws.Cells(1, C) = arrHeadingsToDelete(R) Then 'If there is a match
ws.Cells(1, C).EntireColumn.Delete 'Delete the column...
Exit For '...and move to check the next one
End If
Next R
Next C
End Sub