简体   繁体   中英

Excel Vlookup with Autofill VBA

I'm trying to make a macro that seems pretty simple, but it's proven to be harder than I thought. I started making it using the "point and click" method, but it hasn't been as dynamic as I had thought. Basically I'm using vlookup to look up the names in cell A2 from another worksheet, then copy numbers in column D over to the current sheet. When looking at the code, it looks something like this for this part:

Range("D2").Select
ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(RC[-3],'Downstairs'!R[-1]C[-3]:R[200]C[14],4,0)"

Range("D2").Select
Selection.AutoFill Destination:=Range("D2:D" & lastrow&)

After I find the first number, I'm trying to autofill the rest. It works when you run it but I think it's just because the names are in order. However, if the names aren't in order it won't find the correct number, partly because all the numbers inside the R[] and C[] keep changing as you go down the rows. I don't think it will work if I add more names to the list, which is something I need for it to do. I changed the number inside the R[] from 93 to 200 because I don't really know how to incorporate the lastrow object I had made before, and I don't know of another way to make this dynamic. Is there a better way to do this?

Like I mentioned in my comment above, you do not need VBA for this. You can directly type the formula in Excel and do a manual Autofill. Having said that if you still want to do VBA then simply use this code where you do not need to use AutoFill. This code will fill all the relevant cells with formulas.

Your formula was also not giving you the right results as your table array was not constant and it was changing as you moved down. To prevent that from happening, simply use $ sign.

Another Tip: R1C1 format is very confusing if you are not good with it. Stick to the normal A1 formatting.

Here is the most simple way to achieve what you want. Please amend the code to suit your needs

Sub Sample()
    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim lastrow  As Long

    '~~> Change this to the releavnt sheet name
    '~~> This is the sheet where the formula will go
    Set ws1 = ThisWorkbook.Sheets("Sheet1")

    Set ws2 = ThisWorkbook.Sheets("Downstairs")

    With ws1
        '~~> Get the last row
        lastrow = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> Fill formula in all the relevant cells in one go
        '~~> replace my formula within quotes with your formula
        '~~> Do not forget to put the $ sign like I have done
        .Range("D1:D" & lastrow).Formula = "=VLOOKUP(A1,Downstairs!$C$1:$N$200,4,0)"
    End With
End Sub

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