Delete multiple columns using column numbers

前端 未结 2 2046
温柔的废话
温柔的废话 2021-01-06 02:39

Just wanted to share as I had huge amount of trouble looking for ways to do this online and have finally gotten it through series of trial and error.

Sheet1.Range(Ce

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-06 03:25

    More ways

    Deleting consecutive columns like 1 - 100

    Sub Sample()
        With Sheet1
            'A:CV
            .Columns(ReturnName(1) & ":" & ReturnName(100)).Delete Shift:=xlToLeft
        End With
    End Sub
    
    '~~> Returns Column Name from Col No
    Function ReturnName(ByVal num As Integer) As String
        ReturnName = Split(Cells(, num).Address, "$")(1)
    End Function
    

    Deleting non consecutive columns like 1, 3, 5

    Sub Sample()
        With Sheet1
            'A:A,C:C,E:E
            .Range( _
                    ReturnName(1) & ":" & ReturnName(1) & "," & _
                    ReturnName(3) & ":" & ReturnName(3) & "," & _
                    ReturnName(5) & ":" & ReturnName(5) _
                   ).Delete Shift:=xlToLeft
        End With
    End Sub
    
    Function ReturnName(ByVal num As Integer) As String
        ReturnName = Split(Cells(, num).Address, "$")(1)
    End Function
    
    '**Another way**
    
    Sub Sample()
        Dim Rng As Range
    
        With Sheet1
            Set Rng = Union(.Columns(1), .Columns(3), .Columns(5))
        End With
    
        Rng.Delete Shift:=xlToLeft
    End Sub
    

提交回复
热议问题