Search code examples
excelvbaexcel-r1c1-notation

How to use R1C1 formatted text in a formula


In order to get dynamic formulas to develop through VBA, I had to use INDIRECT(ADDRESS(. I am now stuck with several dozen formulas that look like this:

=INDIRECT(ADDRESS(37,10),1)*(INDIRECT(ADDRESS(37,7),1)+(INDIRECT(ADDRESS(69,10),1)*INDIRECT(ADDRESS(77,10),1))+(INDIRECT(ADDRESS(70,10),1)*INDIRECT(ADDRESS(78,10),1))+(INDIRECT(ADDRESS(71,10),1)*INDIRECT(ADDRESS(79,10),1))+(INDIRECT(ADDRESS(72,10),1)*INDIRECT(ADDRESS(80,10),1))+(INDIRECT(ADDRESS(73,10),1)*INDIRECT(ADDRESS(81,10),1))+(INDIRECT(ADDRESS(74,10),1)*INDIRECT(ADDRESS(82,10),1))+(INDIRECT(ADDRESS(75,10),1)*INDIRECT(ADDRESS(83,10),1)))

I cannot use these formulas with Solver because it is too much for Solver. When I manually translate the formulas to "A1" format, then Solver works. I need to automate the translation because this is meant to be a template.

I was hoping that replacing "INDIRECT(ADDRESS" with "Cells" might work. No luck. Is there an expression I can use that can replace "INDIRECT(ADDRESS" that will read the R1C1 format? Or do you have a better solution?

Thanks!

 r = 0
    Do Until r = 6
        i = 0
        Do Until i = DCShipFrom
        Cells(70 + r, 7 + DCShipFrom + i).Select
        Selection.FormulaR1C1 = "=IF(AND(INDIRECT(ADDRESS(" & 67 & "," & 7 + DCShipFrom + i & "),1)<=" & "INDIRECT(ADDRESS(" & 70 + r & "," & 6 & "),1)," & "INDIRECT(ADDRESS(" & 67 & "," & 7 + DCShipFrom + i & "),1)>" & "INDIRECT(ADDRESS(" & 69 + r & "," & 6 & "),1)),1,0)"
        i = i + 1
        Loop
    r = r + 1
    Loop
    enter code here

Solution

  • Try this, it makes the formulas dynamic, but much simpler:

    For r = 0 To 6
        For i = 0 To DCShipFrom
            With ActiveSheet
                .Cells(70 + r, 7 + DCShipFrom + i).Formula = "=IF(AND(" & .Cells(67, 7 + DCShipFrom + i).Address(0, 0) & "<=" & .Cells(70 + r, 6).Address(0, 0) & "," & .Cells(67, 7 + DCShipFrom + i).Address & " >" & .Cells(69 + r, 6).Address & "),1,0)"
            End With
        Next i
    next r
    

    Or if you want R1C1:

    For r = 0 To 6
        For i = 0 To DCShipFrom
            With ActiveSheet
                .Cells(70 + r, 7 + DCShipFrom + i).FormulaR1C1 = "=IF(AND(R" & 67 & "C" & 7 + DCShipFrom + i & " <= R" & 70 + r & "C" & 6 & ",R" & 67 & "C" & 7 + DCShipFrom + i & " > R" & 69 + r & "C" & 6 & "),1,0)"
            End With
        Next i
    Next r