vba - Excel VBA : Cannot delete multi columns by using if statement and for loop

标签 vba excel excel-formula

  • 背景和目的。
    我想根据特定的列标题删除“sheet1”中的多列。

  • 例如:如果列名 = “First Name”、“Surname”、“DoB”、“Gender”、“Year”
    然后删除整个列。

    我使用 vba 来做到这一点。
  • “执行”表中的“执行”按钮
  • 数据保存在“Sheet1”中。
  • 单击“执行”按钮,将执行宏并编辑“sheet1”中的数据。

  • 这是我的代码
    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
  • 问题 :当我通过单击“执行”按钮执行我的宏时,当时只删除了 1 列。下一步单击→ 删除下一列(只需单击即可删除一列)。
  • 问题 : 为什么我不能用我的代码一键删除所有列?
    在这种情况下有什么问题?

  • 任何帮助将不胜感激。
    非常感谢您的关注。

    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/

    相关文章:

    vba - 运行时错误1004 excel找不到文本文件来刷新此外部范围

    python - 我有一个包含文本和计算的 Excel 文件,在 python 中读取 Excel 文件的最佳方法是什么?

    excel - 从 Excel vba 将“适合”设置为“在 Pdf 中可见”

    excel - 基于单元格文本值在 Excel 工作表中动态求和

    excel公式根据条件过滤范围

    vba - 将 Variant 数组传递给 sub, "Expected: ="

    excel - 定义范围并清除其内容

    excel - 将多个工作簿中的工作表复制到当前工作簿中

    vb.net - 如何使用vb.net将datagridview导出到excel?

    excel - 如何计算 Excel 中每一行的五分位数?