简体   繁体   中英

Copying formulas to last row of data

I can see the question has been asked a couple of times in the forum, but as someone who doesn't really know macro, I cannot implement the code provided in the answers.

So I have recorded the below macro.

Macro6 Macro
'

'


 Range("C2").Select
    ActiveCell.FormulaR1C1 = _
        "=INDEX('Account codes'!C[-1],MATCH(DATA!RC[4],'Account codes'!C[-2],0))"
    Range("C2").Select
    ActiveCell.FormulaR1C1 = _
        "=INDEX('Account codes'!C2,MATCH(DATA!RC[4],'Account codes'!C1,0))"
    Range("C2").Select
    Selection.Copy
    Range("E2").Select
    ActiveSheet.Paste
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = _
        "=INDEX('Account codes'!C2,MATCH(DATA!RC[4],'Account codes'!C1,0))"
    Range("E2").Select
    ActiveCell.FormulaR1C1 = _
        "=INDEX('Account codes'!C2,MATCH(DATA!RC[3],'Account codes'!C1,0))"
    Range("E2").Select
    Selection.AutoFill Destination:=Range("E2:E4")
    Range("E2:E4").Select
    Range("C2").Select
    Selection.AutoFill Destination:=Range("C2:C4")
    Range("C2:C4").Select

End Sub

In simple terms, I want Selection.AutoFill Destination:=Range("E2:E4") to fill down to the last row of data, and not just to E4. That is because the data can change in size.

How do I do this?

You seem to be overwriting some of the formulas with different relative/absolute references. It really doesn't seem to matter which is used as far as relative/absolute addressing is concerned but you have two distinct formulas for column E which reference two different cells on the data worksheet. I'll use the latter of the two.

Put all of the formulas into all of the cells at once. AutoFill is overrated and functionally redundant in this case.

The formulas for column C seem to be using a relative reference to a cell in column F. You can use that column to determine the last row to put formulas into.

sub buildFormulas()

    dim lr as long

    with worksheets("data")

        lr = .cells(.rows.count, "F").end(xlup).row

        .range(.cells(2, "C"), .cells(lr, "C")).formular1c1 = _
          "=INDEX('Account codes'!C2, MATCH(RC7, 'Account codes'!C1, 0))"

        .range(.cells(2, "E"), .cells(lr, "E")).formular1c1 = _
          "=INDEX('Account codes'!C2, MATCH(RC8, 'Account codes'!C1, 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