Chris2015
Chris2015

Reputation: 1050

Using LastRow in a Range

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

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?

Upvotes: 2

Views: 79376

Answers (1)

Scott Holtzman
Scott Holtzman

Reputation: 27269

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$2:$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 UsedRange could 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.

Upvotes: 5

Related Questions