簡體   English   中英

根據列名刪除指定列

[英]Delete specified column based on column name

我是 VBA 宏的新手,我想從名為 POL 的工作表中刪除一些特定的列。 我的編碼如下,但是,下面的代碼只是執行但不會從表 POL 中刪除指定的列。 宏只是在執行,但沒有彈出任何錯誤。 我沒有從下面的宏中獲得輸出,請幫助..... 我想使用宏刪除數組中指定的幾列。 我只想刪除幾列的 POL 表

Private Sub CommandButton2_Click()

Dim currentSht As Worksheet
Dim i As Long, j As Long
Dim lastRow As Long, lastCol As Long
Dim startCell As Range
Dim colnames
Dim here As Boolean

colnames = Array("Shipment Details", "Full In Gate at Ocean Terminal (CY or Port)", "Vessel Estimated Time of Arrival", "Vessel Arrived at Port of Discharge", "View Docs")

Set currentSht = Worksheets("POL")

Set startCell = currentSht.Range("A1")

lastRow = startCell.SpecialCells(xlCellTypeLastCell).Row
lastCol = startCell.SpecialCells(xlCellTypeLastCell).Column

With currentSht
    For i = lastCol To 1 Step -1
        here = False
        For j = LBound(colnames) To UBound(colnames)
            If .Cells(1, i).Value = colnames(j) Then
                here = True
                Exit For
            End If
        Next j
        If Not here Then
            Columns(i).EntireColumn.Delete
        End If
    Next i
End With
End Sub

更簡單的方法:循環名稱數組,使用 Match 定位列。 如果找到,刪除它

Private Sub CommandButton2_Click()

Dim currentSht As Worksheet
Dim j As Long
Dim colnames, Idx

colnames = Array("Shipment Details", "Full In Gate at Ocean Terminal (CY or Port)", "Vessel Estimated Time of Arrival", "Vessel Arrived at Port of Discharge", "View Docs")

Set currentSht = Worksheets("POL")

With currentSht
    For j = LBound(colnames) To UBound(colnames)
        Idx = Application.Match(colnames(j), .Rows(1), 0)
        If Not IsError(Idx) Then
            .Columns(Idx).Delete
        End If
    Next
End With
End Sub

如果任何列標題可能有多個實例

    For j = LBound(colnames) To UBound(colnames)
        Idx = Application.Match(colnames(j), .Rows(1), 0)
        Do Until IsError(Idx)
            .Columns(Idx).Delete
            Idx = Application.Match(colnames(j), .Rows(1), 0)
        Loop
    Next

暫無
暫無

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

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