簡體   English   中英

Excel VBA:無法通過使用if語句和for循環刪除多列

[英]Excel VBA: Cannot delete multi columns by using if statement and for loop

  1. 背景和目的。 我想根據特定的列標題刪除“ sheet1”中的多列。

例如:如果列名=“名字”,“姓氏”,“ DoB”,“性別”,“年份”,則刪除整個列。

我使用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

sheet1中的樣本數據表

  1. 問題 :當我通過單擊“執行”按鈕執行宏時,當時僅刪除了1列。 下一步→刪除下一列(只需單擊一下即可刪除1列)。
  2. 問題 :為什么我單擊代碼不能一鍵刪除所有列? 在這種情況下有什么問題?

任何幫助將不勝感激。 非常感謝您的關注。

在找到的單元格之前插入新列

以相反的順序遍歷各列。 為此,請更改行:

 For i = 1 To LastCol

至:

 For i = LastCol to 1 Step -1

另一種快速的方法

Option Explicit

Sub SPO_EditDocument_BUttonClick()
    Dim colNames As Variant, colName As Variant, actualColNames As Variant, foundColName As Variant
    Dim colsToDelete As String

    colNames = Array("Firstname", "Surname", "DoB", "Gender", "Year") ' build a list of column headers to be deleted

    With Worksheets("Sheet1") ' reference data sheet
        actualColNames = Application.Index(.Range("A1", .Cells(1, .Columns.count).End(xlToLeft)).Value, 1, 0) ' collect referenced sheet actual column headers

        For Each colName In colNames ' loop through your column headers to be deleted list
            foundColName = Application.Match(colName, actualColNames, 0) ' try finding current header to be deleted in actual headers list
            If Not IsError(foundColName) Then colsToDelete = colsToDelete & Columns(foundColName).Address(False, False) & " " 'if found update columns to be deleted index list
        Next

        If colsToDelete <> "" Then .Range(Replace(Trim(colsToDelete), " ", ",")).EntireColumn.Delete ' if columns to be deleted index list not empty, then delete thsoe columns
    End With

刪除多個列的一種更快的方法是使用Range對象,在我的代碼中是DelRng ,它使用Union函數合並通過要刪除的所有符合條件的Columns 因此,最后,您只需使用Delete函數,該函數需要很長時間才能處理一次。

您可以用Select Case替換多個ElseIf

嵌套在With Worksheets("Sheet1")所有對象無需再次具有With Worksheets("Sheet1") ,只需使用即可. 作為所有CellsRange對象的前綴。

您可以使用更短,更快的代碼版本,例如以下代碼:

修改后的代碼

Sub SPO_EditDocument_BUttonClick()

'Declare constant variable
Dim CellValue As String
Dim DelRng As Range

'Edit SPO Documents.
'Consider worksheet"SPO"

Application.ScreenUpdating = False

With Worksheets("Sheet1")

    '1. Loop and delete unnecessary columns
    LastCol = .Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

    For i = 1 To LastCol
        CellValue = .Cells(1, i)   'Get Column header

        Select Case CellValue
            Case "Firstname", "Surname", "DoB", "Gender", "Year"
                If Not DelRng Is Nothing Then
                    Set DelRng = Application.Union(DelRng, .Columns(i))
                Else
                    Set DelRng = .Columns(i)
                End If

            Case Else
                ' Do nothing

        End Select
    Next i

End With  'End to process Worksheets

' if there's at least 1 column in DelRng >> delete the entire range (all columns) in 1-shot
If Not DelRng Is nothign Then DelRng.Delete

Application.ScreenUpdating = True

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM