[英]How to delete a specified number of columns based on the last column using VBA?
我有以下代碼:
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
當我運行宏時,最后一列被刪除。 但是,我要刪除從最后開始的5列,而不是一列。 我怎樣才能做到這一點?
我想介紹...
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
像這樣嘗試...
With ThisWorkbook.Sheets("Sheet1")
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
.Range(.Cells(1, LastCol - 4), .Cells(1, LastCol)).EntireColumn.Delete
End With
或者,您可以聲明一個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
編輯:
如果要控制要從工作表的單元格中刪除的列數,可以按照以下方法進行操作...
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.