简体   繁体   中英

How do I add a formula with VBA that refers to another cell?

I searched but didn't found what I was looking for. My goal is to have a big number of cells that shows the value of other cells in other sheets like a simple "=january!BP$43". But I want to add this with a loop, here a simplified example:

  For sorte = 0 To 5
    For mois = 0 To 11
        Sheets(2).Range(4+k, 1 + mois + j).Formula = "=Sheets(3 + mois).Cells(40+i, 2 + sorte)"
    Next
    j = j + 13
    i=i+15
    k=k+1
Next

I tried it without the " " around "Sheets...)" and it works but just inserts the value and not the formula. Any Idea? Thanks a lot

PS: j,i,k are just here to show that I have other variables coming there to change the position.

Remember that everything in between quotation marks will be copied as a string. You need to close the quotation marks whenever you want to use the value of the variable, not the variable name:

For mois = 0 To 11
    Sheets(2).Range(4+k, 1 + mois + j).Formula = "=Sheets(" & 3 + mois & ").Cells(" & 40+i & "," & 2 + sorte& ")"
Next

However, wouldn't it be easier to just use Excel and copy to the cells you need?

You will need to place the sheet name in using Sheets(3 + mois).Name , and it will be easiest to refer to the row and column using R1C1 notation:

For sorte = 0 To 5
    For mois = 0 To 11
        Sheets(2).Cells(4+k, 1 + mois + j).FormulaR1C1 = "='" & Sheets(3 + mois).Name & "'!R" & (40+i) & "C" & (2 + sorte)
    Next
    j = j + 13
    i=i+15
    k=k+1
Next

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