简体   繁体   中英

VLookup function range in Excel using macro

I am trying to make a macro to do the vlookup in excel. I have succeed to create and the code is working fine! The code as below:

ActiveCell.FormulaR1C1 = _ "=VLOOKUP(RC[-1],LW0640!R2C8:R12163C9,2,TRUE)" Selection.AutoFill Destination:=Range("D6:D6098")

However, I found that the range is fix range. which is from D6:D6098 on the result and R2C8:R12163C9 from the source.

And it will not work if the data range changes. I want to know how to make the range for the vlookup function from the beginning until the last row in the range. Please help!

You can use the "A1" type of notation. In your case, you want column 8 and 9, which are respectively H and I, so you can write the following:

ActiveCell.FormulaR1C1 = _
"=VLOOKUP(RC[-1],LW0640!H:I" & MyCols & ",2,TRUE)"
Selection.AutoFill Destination:=Range("D6:D6098")

You can use this code.

Sheets("LW0640").Select
Range("D6:D6098").Select
    ActiveWorkbook.Names.Add Name:="tablex", RefersToR1C1:= _
        "=LW0640!R6C4:R6098C4"


'Range("F28").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-1],tablex,2,TRUE)"

Try

Sub Demo()
    Dim ws As Worksheet
    Dim LastRow As Long

    Set ws = ThisWorkbook.Sheets("Sheet1")  'change Sheet1 to your data sheet
    With ws
        LastRow = .Range("H" & .Rows.Count).End(xlUp).Row
        .Range("D6:D" & LastRow).Formula = "=VLOOKUP(C6,LW0640!$H$2:$I$" & LastRow & ",2,TRUE)"
    End With
End Sub

You should avoid using SELECT and ACTIVE . See this for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM