繁体   English   中英

如何使用VBA根据最后一列删除指定的列数?

[英]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.

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