Search code examples
excelvbaformulacell

Copy the formula in Excel as it is done by dragging the cell over to another


For i = 1 To staffelRange.Rows.Count
   .DataBodyRange.Cells(i, countHeader).Formula = staffelRange.Cells(i).Formula
Next

the code works as intended and copies the formulas from my range into the desired range in my table. first to the formula, the formula always refers to the column header and the cell left of it, if i copy the code now with my function from column 1 to for example column 4, the formula still refers to column 1 instead of column 4. but if i copy it by dragging the formula over to the other cell, the formula adapts. How can I achieve such an adjustment in my code? Formula: =$G39*(1+SVERWEIS(Stückpreise_neu_19[[#Kopfzeilen];[Staffel1]];Rabattstaffel_new_24;2;FALSCH))


Solution

  • If the formula is always the same except for the cell reference, you can just write the formula to sheet as a string value with a variable for the correct row number.

    Something like...

    For i = 1 To staffelRange.Rows.Count
       .DataBodyRange.Cells(i, countHeader).Formula = "=$G" & i & "*1+SVERWEIS(Stückpreise_neu_19[[#Kopfzeilen];Staffel1]];Rabattstaffel_new_24;2;FALSCH))"
    Next
    

    This is assuming your variable i represents the correct row number for the formula (which to my understanding is correct).