vbaexcel-formulaexcel-r1c1-notation

VBA - Maintain cell formula integrity


I am having a difficult time inputting an Indirect formula into my code. I understand that I can use a FormulaR1C1, however that creates a formula in the cell that is fairly static and is not too kind when adding rows after I run my code. I'd like my code to be something like this in-cell formula =SUM(L99:INDIRECT("R[-1]C",0)), which resides in cell L106.

Formula Screenshot

Below is my code as well as my attempt at creating the above formula. Thanks!

   Dim s1 As Excel.Worksheet: Set s1 = ActiveWorkbook.Worksheets(ThisWorkbook.Sheets.Count)

   With s1

        'What the current formula is
        .Cells(rwCnt, abRng.Column).Offset(4, 6).FormulaR1C1 = "=sum(R[0]C[-5],R[0]C[-2])"
        .Cells(rwCnt, abRng.Column).Offset(11, 6).FormulaR1C1 = "=Sum(R[-7]C[0]:R[-1]C[0])"

        'My attempt
        .Cells(rwCnt, abRng.Column).Offset(11, 6).Formula = "=sum(" & .Cells(rwCnt, abRng.Column).Offset(4, 6) _
            & ":INDIRECT(""R[-1]C"", 0))"

   End With


Solution

  • .Cells(rwCnt, abRng.Column).Offset(4, 6) i think this will be returning the value in the cell, where you need the address of it

    For example cells(1,1) would return a value, where cells(1,1).address would return $A$1