2013-09-23 829 views
3

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

E.g.我想从我的电子表格中选择1,2,3,4,然后删除选择。

数据:

John | 10 | 10 | 10 
Smith | 5 | 5 | 5 
Fred | 8 | 8 | 8 
1  | 2 | 3 | 4 

这里是我的代码,它只能在A柱选择了最后一排。 (选择1并删除它)。我需要它来选择1到4并删除整行。

Range("A" & Rows.Count).End(xlUp).Select 
Selection.Delete Shift:=xlUp 

回答

12

这是你正在尝试?我已经评论了代码,以便您不会有任何理解它的问题。

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 

顺便说一句我假设LastRow是所有行相同和列的相同。如果不是这种情况,那么您将使用.Find来查找最后一行和最后一列。你可能想看看THIS

+0

我把'Selection.Delete移:= xlUp' With rng代码块但它不会删除选择 – user2273278

+0

它不会;)尝试'.Delete Shift:= xlUp'在调试语句之后。 –

+0

它似乎仍然不起作用 – user2273278

3

最简单的修改(在你的问题的代码)是这样的:

Range("A" & Rows.Count).End(xlUp).Select 
    Selection.EntireRow.Delete 

这可以简化为:

Range("A" & Rows.Count).End(xlUp).EntireRow.Delete 
相关问题