【发布时间】: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作为是否删除列的测试?