【问题标题】:Delete specified column based on column name根据列名删除指定列
【发布时间】:2020-10-05 17:28:09
【问题描述】:

我是 VBA 宏的新手,我想从名为 POL 的工作表中删除一些特定列。我的编码如下,但是,下面的代码只是执行但不会从工作表 POL 中删除指定的列。宏正在执行,但没有弹出任何错误。我没有从下面的宏中得到输出,请帮助.....我想使用宏删除数组中指定的几列。 POL Sheet where I want to delete only a few columns

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

【问题讨论】:

  • lastcol 的值是多少?当here=False 时也会触发If Not here Then
  • 你跳出j循环,设置here=True,然后你用Not here作为是否删除列的测试?

标签: excel vba


【解决方案1】:

更简单的方法:循环 names 数组,使用 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

【讨论】:

  • 这是一种巧妙的做法。唯一的问题是任何 colnames 是否多次出现,因为此代码只会删除第一个实例。
  • 如果这是一个要求,只需循环匹配/删除位直到 IsError。 OP 中没有表明它是必需的
  • 感谢@chrisneilsen 的解释,它起作用了...
猜你喜欢
  • 2022-10-15
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2015-04-16
  • 2022-12-07
  • 1970-01-01
  • 2013-06-17
相关资源
最近更新 更多