我有一组数据,其中每三列都是相同的。我只想留下第一列,其他相同的必须删除。
起初我尝试了这段代码,但它删除了错误的列,因为在每个循环中其他列的位置都被改变了。
Sub DeleteMultipleColumns()
Dim i As Integer
Dim LastColumn As Long
Dim ws As Worksheet
Set ws = Sheets("Arkusz2")
LastColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column
ws.Activate
For i = 4 To (LastColumn - 2)
ws.Columns(i).Select
Selection.Delete Shift:=xlToLeft
i = i + 3
Next i
End Sub
在此之后,我尝试了另一个使用 Union。它也不起作用:
Sub DeleteMultipleColumns()
Dim i As Integer
Dim LastColumn As Long
Dim ws As Worksheet
Set ws = Sheets("Arkusz2")
LastColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column
ws.Activate
For i = 4 To (LastColumn - 2)
Application.Union.Columns(i).Select
i = i + 3
Next i
Selection.Delete Shift:=xlToLeft
End Sub
那么该怎么做呢?
我的新想法是尝试使用数组。我还有其他选择吗?
这是我在您给出很好的答案后实现的代码(感谢:sam092、meohow、mattboy):
Sub DeleteMultipleColumns()
Dim i As Integer
Dim LastColumn As Long
Dim ws As Worksheet
Application.ScreenUpdating = False
Set ws = Sheets("Arkusz2")
LastColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column - 2
For i = LastColumn To 4 Step -3
ws.Columns(i).Delete Shift:=xlToLeft
Next i
Application.ScreenUpdating = True
End Sub