简体   繁体   中英

How to delete a specified number of columns based on the last column using VBA?

I have the following code:

Sub BlaBla()
Dim LastCol As Long

With ThisWorkbook.Sheets("Sheet1")
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    .Columns(LastCol).Delete
End With
End Sub

When I run the Macro, the last column is deleted. However, I want to delete say, 5 columns starting from the last, rather than one. How can I do this?

I would like to present...

Sub DeleteLast5()
    With ThisWorkbook.Sheets("Sheet2")
        With .Cells(1, .Columns.Count).End(xlToLeft)
            If .Column > 5 Then
                .Offset(0, -4).Resize(, 5).Delete
            Else
                .Columns("A:E").Delete
            End If
        End With
    End With
End Sub

Try it like this...

With ThisWorkbook.Sheets("Sheet1")
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    .Range(.Cells(1, LastCol - 4), .Cells(1, LastCol)).EntireColumn.Delete
End With

Or you can declare a Constant Variable to hold the number of columns to be deleted which you can change if required.

Const DelCnt As Integer = 5
Sub BlaBla()
Dim LastCol As Long
With ThisWorkbook.Sheets("Sheet1")
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    .Range(.Cells(1, LastCol - DelCnt + 1), .Cells(1, LastCol)).EntireColumn.Delete
End With
End Sub

Edit:

If you want to control the number of columns to be deleted from a cell on the sheet, you can follow this approach...

Sub BlaBla()
Dim LastCol As Long
Dim DelCnt As Integer
DelCnt = Sheets("Sheet2").Range("E18").Value
With ThisWorkbook.Sheets("Sheet1")
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    If LastCol >= DelCnt Then
        .Range(.Cells(1, LastCol - DelCnt + 1), .Cells(1, LastCol)).EntireColumn.Delete
    End If
End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM