我有一组数据,其中每三列都相同。我想只留下第一列,必须删除其他相同的列。
起初我尝试了这段代码,但它删除了错误的列,因为在每个循环中其他列的位置都被更改了。
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
答案 0 :(得分:5)
扭转方向。从右侧开始删除。我想你知道如何修改你的代码
答案 1 :(得分:3)
你可以像这样倒退。此外,您不需要在删除之前选择列,您可以立即删除它。
For i = ((LastColumn \ 4) * 4) To 4 Step -4
ws.Columns(i).Delete Shift:=xlToLeft
Next i
答案 2 :(得分:1)
我赞成Mattboy的代码是最干净的
可以避免使用范围循环并按照你的建议使用数组,尽管我发布了更多内容,因为数组生成很棘手
使用Is it possible to fill an array with row numbers which match a certain criteria without looping?
Sub OneinThree()
Dim ws As Worksheet
Dim rng1 As Range
Dim x As String
Set ws = ActiveSheet
Set rng1 = Cells(1, ws.Cells(1, Columns.Count).End(xlToLeft).Column - 2)
x = Join(Filter(Application.Evaluate("=IF(MOD(column(A1:" & rng1.Address & "),3)=0,address(1,column(a1:" & rng1.Address & ")),""x"")"), "x", False), ",")
If Len(x) > 0 Then ws.Range(x).EntireColumn.Delete
End Sub