Excel VBA选择最后一行和列的范围

use*_*278 4 excel vba excel-vba

我正在尝试创建一个macro选择最后一行和最后一列的范围.

例如,我想从电子表格中选择1,2,3,4,然后删除选择.

数据:

John  | 10 | 10 | 10
Smith | 5  | 5  | 5
Fred  | 8  | 8  | 8 
1     | 2  | 3  | 4
Run Code Online (Sandbox Code Playgroud)

这是我的代码,它只选择A列的最后一行.(选择1并删除它).我需要它来选择1到4并删除整行.

Range("A" & Rows.Count).End(xlUp).Select
Selection.Delete Shift:=xlUp
Run Code Online (Sandbox Code Playgroud)

Sid*_*out 13

这是你在尝试什么?我已对代码进行了评论,以便您在理解代码时不会遇到任何问题.

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long, lCol As Long
    Dim rng As Range

    '~~> Set this to the relevant worksheet
    Set ws = [Sheet1]

    With ws
        '~~> Get the last row and last column
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

        '~~> Set the range
        Set rng = .Range(.Cells(lRow, 1), .Cells(lRow, lCol))

        With rng
            Debug.Print .Address
            '
            '~~> What ever you want to do with the address
            '
        End With
    End With
End Sub
Run Code Online (Sandbox Code Playgroud)

顺便说一下,我假设LastRow所有行都是一样的,列也一样.如果不是这种情况,那么您将使用.Find查找最后一行和最后一列.你可能想看到这个


小智 5

最简单的修改(对您问题中的代码)是这样的:

    Range("A" & Rows.Count).End(xlUp).Select
    Selection.EntireRow.Delete
Run Code Online (Sandbox Code Playgroud)

可以简化为:

    Range("A" & Rows.Count).End(xlUp).EntireRow.Delete
Run Code Online (Sandbox Code Playgroud)