Excel VBA 在最后一行和最后一列选择范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18952362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA select range at last row and column
提问by user2273278
I'm trying to create a macro
that selects the range of last row and last column.
我正在尝试创建一个macro
选择最后一行和最后一列的范围。
E.g. I want to select 1, 2, 3, 4 from my spreadsheet and then delete the selection.
例如,我想从电子表格中选择 1、2、3、4,然后删除选择。
Data:
数据:
John | 10 | 10 | 10
Smith | 5 | 5 | 5
Fred | 8 | 8 | 8
1 | 2 | 3 | 4
Here is my code, it only selects the the last row on the A column. (selects 1 and deletes it). I need it to select 1 to 4 and delete the whole row.
这是我的代码,它只选择 A 列的最后一行。(选择 1 并删除它)。我需要它来选择 1 到 4 并删除整行。
Range("A" & Rows.Count).End(xlUp).Select
Selection.Delete Shift:=xlUp
回答by Siddharth Rout
Is this what you are trying? I have commented the code so that you will not have any problem understanding it.
这是你正在尝试的吗?我已经对代码进行了注释,以便您理解它不会有任何问题。
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
BTW I am assuming that LastRow
is the same for all rows and same goes for the columns. If that is not the case then you will have use .Find
to find the Last Row and the Last Column. You might want to see THIS
顺便说一句,我假设LastRow
所有行都相同,列也是如此。如果不是这种情况,那么您将不得不使用.Find
找到最后一行和最后一列。你可能想看这个
回答by Chuck Trese
The simplest modification (to the code in your question) is this:
最简单的修改(对您问题中的代码)是这样的:
Range("A" & Rows.Count).End(xlUp).Select
Selection.EntireRow.Delete
Which can be simplified to:
可以简化为:
Range("A" & Rows.Count).End(xlUp).EntireRow.Delete
回答by Crowdpleasr
Another simple way:
另一种简单的方法:
ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).Select
Selection.EntireRow.Delete
or simpler:
或更简单:
ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).EntireRow.Delete