首页 > 解决方案 > Excel VBA - 在最后占用的列和行之后选择所有列和行

问题描述

我试图找出标识工作表中最后一个占用列的代码,然后删除之后的所有列。我还试图找出标识工作表中最后占用行的代码,然后删除之后的所有行。

到目前为止,我的想法是我需要使用Rows.Count函数,但我无法让它在最后一个占用的行之后选择整行。列也一样...这是我迄今为止提出的,它只识别最后一个占用的行。有谁知道如何让它在此之后现在选择整行?同样对于整个列?我似乎无法弄清楚代码来选择最后一个占用的列,就像我可以用行一样......提前谢谢你

行: Sheets("ppCopy").Cells(Rows.Count, 1).End(xlUp).Row

标签: vbaexcel

解决方案


您需要阅读代码并尝试理解它,答案就会出现。

分解你已经知道的。

Sheets("ppCopy").Cells(Rows.Count, 1).End(xlUp).Row

Rows.Count = 最后可用行

End(xlUp) = 从最后一个可用行 (Rows.Count) 向上移动到最后使用的行。

那你怎么得到专栏呢?

Sheets("ppCopy").Cells(1, Columns.Count).End(xlToLeft).Column

Columns.Count = 最后可用的列

End(xlToLeft) = 从最后一个可用列 (Columns.Count) 向左移动到最后一个使用的列。

以下是如何删除未使用的行和列:

Sub deleteUnused()
    Dim lastRow As Long, lastColumn As Integer 'there are a lot of rows compared to columns
    Dim lastLetter As String, firstLetter As String
    Set wk = ThisWorkbook
    With wk.Sheets("Sheet1")
        'Get last used rows and columns based on valued from Column A and Row 1
        lastRow = .Cells(Excel.Rows.Count, 1).End(Excel.xlUp).Row
        lastColumn = .Cells(1, Excel.Columns.Count).End(Excel.xlToLeft).Column
        'Delete Rows
        .Rows("" & (lastRow + 1) & ":" & Excel.Rows.Count & "").EntireRow.Delete Shift:=xlUp
        'Delete columns, tricky because you need the Column Letters instead of the numbers
        lastColumn = lastColumn + 1
        firstLetter = Split(.Cells(, lastColumn).Address, "$")(1)
        lastLetter = Split(.Cells(, Excel.Columns.Count).Address, "$")(1)
        .Columns("" & firstLetter & ":" & lastLetter & "").EntireColumn.Delete Shift:=xlLeft
    End With
End Sub

推荐阅读