如何选择和删除每3列 [英] How to select and delete every 3rd column
问题描述
起初我尝试了这个代码,但它删除了错误的列,因为在每个循环中其他列职位被改变
Sub DeleteMultipleColumns()
Dim i As Integer
Dim LastColumn As Long
Dim ws作为工作表
设置ws =表(Arkusz2)
LastColumn = ws.Cells(1,Columns.Count).End(xlToLeft).Column
ws.Activate
对于i = 4到(LastColumn - 2)
ws.Columns(i)。选择
Selection.Delete Shift:= xlToLeft
i = i + 3
下一个
End Sub
此后,我尝试使用联盟的另一个。它不起作用:
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
对于i = 4至(LastColumn - 2)
Application.Union.Columns(i)。选择
i = i + 3
下一个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
设置ws = Sheets(Arkusz2)
LastColumn = ws.Cells(1,Columns.Count).End(xlToLeft).Column - 2
对于i = LastColumn to 4 Step -3
ws.Columns(i).Delete Shift:= xlToLeft
Next i
Application.ScreenUpdating = True
End Sub
反转方向。从右边开始删除。我想你知道如何修改代码
I have a set of data where every third column is the same. I want to leave only the first column and other which are the same must be deleted.
At first I tried this code but it deleted wrong columns because in every loop other columns positions were altered.
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
After this I tried another one using Union. It doesn't work as well:
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
So how to do it?
My new idea is to try with an array. Do I have other options?
This is the code that I've implemented after your very good answers (thanks: 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
Reverse the direction. Start deleting from the right. I think you know how to modify your code
这篇关于如何选择和删除每3列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!