我有以下代码:
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
运行宏时,会删除最后一列。但是,我想删除say,从最后一列开始的5列,而不是一列。我怎么能这样做?
答案 0 :(得分:2)
我想提出......
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
答案 1 :(得分:1)
尝试这样......
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