3

我有一组数据,其中每三列都是相同的。我只想留下第一列,其他相同的必须删除。

起初我尝试了这段代码,但它删除了错误的列,因为在每个循环中其他列的位置都被改变了。

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
4

3 回答 3

5

反转方向。从右边开始删除。我想你知道如何修改你的代码

于 2013-10-09T07:21:27.837 回答
3

你可以像这样倒退。此外,您不需要在删除之前选择列,您可以直接将其删除。

For i = ((LastColumn \ 4) * 4) To 4 Step -4
   ws.Columns(i).Delete Shift:=xlToLeft
Next i
于 2013-10-09T07:29:30.900 回答
1

我赞成 Mattboy 的代码是最干净的

可以避免范围循环并按照您的建议使用数组,尽管由于数组生成很棘手,因此我发布了更多内容

是否可以在不循环的情况下用符合特定条件的行号填充数组?

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
于 2013-10-11T13:40:08.007 回答