Excel VBA - 删除范围中的每个第3和第4列

时间:2016-11-20 17:17:24

标签: excel excel-vba vba

试图找出如何删除范围内的每个第3和第4列。

我知道我可以删除范围内的列:

Columns("C:E").EntireColumn.Delete

但无法弄清楚如何只删除每隔3和4 ......

3 个答案:

答案 0 :(得分:1)

下面的代码删除“Sheet1”中的每个第3和第4列(根据您的需要修改工作表的名称):

Option Explicit

Sub DeleteEvery_ThirdFourthCol()

Dim LastCol As Long
Dim Col As Long

' modify "Sheet1" to your sheet's name
With Sheets("Sheet1")    
    ' find last column with data in row 1 > modify to your needs
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

    ' loop columns backwards when deleting
    For Col = LastCol To 1 Step -1
        If Col Mod 3 = 0 Or Col Mod 4 = 0 Then
            .Range(.Cells(1, Col), .Cells(1, Col)).EntireColumn.Delete
        End If
    Next Col            
End With

End Sub

答案 1 :(得分:1)

如前所述@ YowE3K,目前尚不清楚是否要求:

  1. 删除每个3或4的倍数列(即第3,4,6,8,9,12,15,16,18,20,21,24列等)或
  2. 删除每组4列中的第3和第4列(即第3,4,7,8,11,12,15,16,19,20,23,24等栏)。
  3. 因此,我为每个案例提供了一个独立的解决方案:

    这些解决方案会立即删除工作表UsedRange中符合要求的所有列。

    1.删除3或4的倍数的每列

    Sub Delete_Every_Column_Multiple_Of_3_or_4()
    Dim rTrg As Range, iLstCol As Integer, i As Integer
        With ThisWorkbook.Sheets("Sht(1)")  'Change as required
            iLstCol = .UsedRange.SpecialCells(xlLastCell).Column
            For i = 1 To iLstCol
                If i <> 1 And (i Mod 3 = 0 Or i Mod 4 = 0) Then
                    If rTrg Is Nothing Then
                        Set rTrg = .Columns(i)
                    Else
                        Set rTrg = Union(rTrg, .Columns(i))
            End If: End If: Next
            rTrg.EntireColumn.Delete
        End With
    End Sub
    

    2.删除每组4列中的第3和第4列

    Sub Delete_3rd_And_4th_Column_in_Every_Group_of_Four()
    Dim rTrg As Range
    Dim iLstCol As Integer
    Dim i As Integer
        With ThisWorkbook.Sheets("Sht(2)")  'Change as required
            iLstCol = .UsedRange.SpecialCells(xlLastCell).Column
            For i = 1 To iLstCol
                If i Mod 4 = 0 Or i Mod 4 = 3 Then
                    If rTrg Is Nothing Then
                        Set rTrg = .Columns(i)
                    Else
                        Set rTrg = Union(rTrg, .Columns(i))
            End If: End If: Next
            rTrg.EntireColumn.Delete
        End With
    End Sub
    

    enter image description here 两个案例之前的列。

    enter image description here 两个案例之后的列。

答案 2 :(得分:0)

Public Sub DeleteEveryThirdColumn()
    Const EveryN As Long = 3
    Dim rng As Range: Set rng = ActiveSheet.Range("C:F")
    Dim c As Long: For c = ((rng.Columns.Count - 1) \ EveryN) * EveryN + 1 To 1 Step -EveryN
        rng.Columns(c).Delete
    Next c
End Sub