vba 在范围内使用 LastRow

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13712810/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:32:07  来源:igfitidea点击:

Using LastRow in a Range

excel-vbavbaexcel

提问by Chris2015

I have asked to find the last row in a Range with the following:

我要求使用以下内容在 Range 中查找最后一行:

Dim LastRow As Integer
LastRow = ActiveSheet.UsedRange.Rows.Count

Now, I'd like to select a range with a known column and an unknown last row. I'd like to fill in the entire column without overshooting the rows by insert an exact number. Here is what I have -

现在,我想选择一个具有已知列和未知最后一行的范围。我想通过插入一个确切的数字来填充整个列而不会超出行。这是我所拥有的 -

Range("AA2").Select
ActiveCell.FormulaLocal = "=Vlookup(A2,[CP_QR_5_prep.xlsm]Sheet1!A2:LastRow,18,false)"
Selection.AutoFill Destination:=Range("AA2:AA & LastRow)

How can I correct my syntax and understand how to use lastrow/lastcolumn?

如何更正我的语法并了解如何使用 lastrow/lastcolumn?

回答by Scott Holtzman

You are pretty close.

你很接近。

The syntax you have for these lines:

这些行的语法:

ActiveCell.FormulaLocal = "=Vlookup(A2,[CP_QR_5_prep.xlsm]Sheet1!A2:LastRow,18,false)"
Selection.AutoFill Destination:=Range("AA2:AA & LastRow)

Should be:

应该:

ActiveCell.FormulaLocal = "=Vlookup(A2,[CP_QR_5_prep.xlsm]Sheet1!$A:$A$" & LastRow & ",18,false)" 'i added absolute referencing which I would think you need... if not take out the "$" signs
Selection.AutoFill Destination:=Range("AA2:AA" & LastRow)

Because, in order to read the variable value into your strings, you need to close the strings and concatenate the variable name.

因为,为了将变量值读入您的字符串,您需要关闭字符串并连接变量名称。

I will also add that to get the actual last row of cells with data it's better to do something like this:

我还将添加它以获取带有数据的实际最后一行单元格,最好执行以下操作:

lastRow = Range("A" & Rows.Count).End(xlUp).Row

as using UsedRangecould potentially leave you with an undesired answer if there are cells in the sheets with formatting or other cells that seem to be blank, but are not.

因为UsedRange如果工作表中有格式的单元格或其他似乎为空白但实际上不是空白的单元格,则使用可能会给您带来不希望的答案。