我想根据特定的列标题删除“sheet1”中的多列。
例如:如果列名 = “First Name”、“Surname”、“DoB”、“Gender”、“Year”
然后删除整个列。
我使用 vba 来做到这一点。
这是我的代码
Sub SPO_EditDocument_BUttonClick()
'Declare constant variable
Dim CellValue As String
'Edit SPO Documents.
'Consider worksheet"SPO"
With Worksheets("Sheet1")
'1. Loop and delete unnecessary columns
LastCol = Sheets("Sheet1").Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
For i = 1 To LastCol
On Error Resume Next
CellValue = Sheets("Sheet1").Cells(1, i) 'Get Column header
If CellValue = "Firstname" Then
Sheets("Sheet1").Columns(i).EntireColumn.Delete
ElseIf CellValue = "Surname" Then
Sheets("Sheet1").Columns(i).EntireColumn.Delete
ElseIf CellValue = "DoB" Then
Sheets("Sheet1").Columns(i).EntireColumn.Delete
ElseIf CellValue = "Gender" Then
Sheets("Sheet1").Columns(i).EntireColumn.Delete
ElseIf CellValue = "Year" Then
Sheets("Sheet1").Columns(i).EntireColumn.Delete
End If
Next i
End With 'End to process Worksheets
Application.ScreenUpdating = True
End Sub
Sample data table in sheet1
在这种情况下有什么问题?
任何帮助将不胜感激。
非常感谢您的关注。
Insert new columns before found cells
最佳答案
以相反的顺序循环遍历列。为此,请更改您的线路:
For i = 1 To LastCol
至:
For i = LastCol to 1 Step -1
关于vba - Excel VBA : Cannot delete multi columns by using if statement and for loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49911678/