How to get VLOOKUP to select down to the lowest row in VBA?

久未见 提交于 2019-12-04 06:43:47

问题


Looking to automate the insertion of a VLOOKUP formula in a cell. When recording the macro I instruct it to populate the columns below with the same formula. Works great, however, there is an issue when the table that the VLOOKUP searches through changes (more or less rows).

As it's recorded, the VLOOKUP drops down to the final row in the table (273). However, I want to set it up so that it will go down to the very last row. Meaning that I can run the script on tables of varying numbers of rows.

Selected columns will remain the same.

Range("AJ2").Select
ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(RC[-20], Previous!R2C2:R273C22,17,FALSE)"

回答1:


try this:

With Worksheets("Previous")
    Range("AJ2").FormulaR1C1 = _
        "=VLOOKUP(RC[-20], Previous!R2C2:R" & .Cells(.Rows.Count, 2).End(xlUp).Row & "C22,17,FALSE)"
End With

where:

  • Range("AJ2")

    will implicitly reference the ActiveSheet

  • .Cells(.Rows.Count, 2).End(xlUp).Row

    will reference "Previous" worksheet, being inside a With Worksheets("Previous")- End With block




回答2:


@nbayly said it, plenty of posts on this. Infact i have provided an answer to this before here:

How to Replace RC Formula Value with Variable

below is slightly modified for a dynamic range, which is what i believe you are looking for

For j = n To 10 Step -1
    If Cells(j, 1).Value = "" Then
        Cells(j, 1).Formula = "=VLookup(RC20,Previous!R2C2:R273C22,17,FALSE)"
    End If
Next j

remember to define j as long and n=sheets("sheetname)".cells(rows.count,1).end(xlup).row

replace 10 in j = n to 10 with the starting row number



来源:https://stackoverflow.com/questions/40512439/how-to-get-vlookup-to-select-down-to-the-lowest-row-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!