vba 如何使用变量“最后一行号”在另一列中设置范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19409717/
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
how to use variable "last row number" to set the range in another column
提问by user2887213
The data file has value 1 to 10 from A1 to A10.
数据文件从 A1 到 A10 具有值 1 到 10。
A B
1 1 1
2 2 1
3 3 1
4 4 1
5 5 2
6 6 2
7 7 2
8 8 2
9 9 2
10 10 3
I need insert a column (eg column B) to my data file. In Cell B1 there is a formula (eg: (=INT(A1/5)+1)). I usually double click the right-bottom corner of cell B1, this auto-filling the rest of cells in column B to the row with data in column A (as shown in table above)
我需要在我的数据文件中插入一列(例如 B 列)。在单元格 B1 中有一个公式(例如:(=INT(A1/5)+1))。我通常双击单元格 B1 的右下角,这会自动将 B 列中的其余单元格填充到 A 列中包含数据的行中(如上表所示)
By using record Macro, it gave me codes below:
通过使用记录宏,它给了我以下代码:
Range("B1").Select
Selection.AutoFill Destination:=Range("B1:B10")
Range("B1:B10").Select
The problem is the data files have different last row number with data(it might be row 8 or row 14). So the macro created as above won't fit the other data files.
问题是数据文件的最后一行编号与数据不同(可能是第 8 行或第 14 行)。因此,如上创建的宏将不适合其他数据文件。
I know using macro below, it finds last row with data.
我知道在下面使用宏,它会找到带有数据的最后一行。
lastRow = Range("A99999").End(xlUp).Row
How can I replace B10 in the range "B1:B10" with the variable? I would like to have a common macro. Could someone help on this? Appreciated!!
如何用变量替换“B1:B10”范围内的 B10?我想要一个通用的宏。有人可以帮忙吗?赞赏!!
回答by Joe Laviano
Also, added to my comment, recording is a great tool, but can add some unnecessary "Select" statements. Your lines (with lastrow) can be just:
另外,添加到我的评论中,记录是一个很好的工具,但会添加一些不必要的“选择”语句。您的台词(带有 lastrow)可以是:
Range("B1").AutoFill Destination:=Range("B1:B" & lastrow)
回答by Siddharth Rout
You don't need Autofill for this. You can assign the formula in one go to the entire range
为此,您不需要自动填充。您可以一次性将公式分配到整个范围
Range("B1:B" & Lrow).Formula = "=INT(A1/5)+1"
Where LRow
is the LastRow.
LRow
LastRow在哪里。
lastRow = Range("A99999").End(xlUp).Row
lastRow = Range("A99999").End(xlUp).Row
Please do not hard code values like 99999
to find the last row. See THISon how to find the last row.
请不要硬编码值,例如99999
查找最后一行。有关如何查找最后一行的信息,请参阅THIS。