[英]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.
但是,我要删除从最后开始的5列,而不是一列。 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. 或者,您可以声明一个
Constant Variable
来保存要删除的列数,如果需要,可以更改。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.