0

I am trying to use .formulaR1C1 to sum up values from different sheets on my main sheet for my workbook. Everytime I run through my code it errors on the last bit where the formula is entered.

code:

For cRow = 9 To row
    For Each WS In Worksheets
        If Left(WS.Name, 5) <> "Total" Then
            If Left(WS.Name, InStr(WS.Name, " ") - 1) = "December" Then
                ytdSheet.Cells(cRow, 2).FormulaR1C1 = "=SUM(" & ytdSheet.Cells(cRow, 2).Value & "'" & WS.Name & "'!RC)" 'HERE IS WHERE ERROR OCCURS!!!
            Else
                ytdSheet.Cells(cRow, 2).Value = ytdSheet.Cells(cRow, 2).Value & "'" & WS.Name & "'!RC,"
            End If
        End If
    Next WS
Next cRow

I feel like I am missing something simple, but I cannot figure it out.

3
  • Have you verified that "=SUM(" & ytdSheet.Cells(cRow, 2).Value & "'" & WS.Name & "'!RC)" always produces a valid formula?
    – DeanOC
    Aug 21, 2014 at 21:09
  • debug.print of the line returns: =SUM(January 2014'!RC,'February 2014'!RC,'March 2014'!RC,'April 2014'!RC,'May 2014'!RC,'June 2014'!RC,'July 2014'!RC,'August 2014'!RC,'September 2014'!RC,'October 2014'!RC,'November 2014'!RC,'December 2014'!RC)
    – lpau001
    Aug 21, 2014 at 21:25
  • 4
    So if you paste that into a cell in your spreadsheet, does it evaluate without an error? Your formula seems to be missing a quote in front of January, so I would be surprised if it did.
    – DeanOC
    Aug 21, 2014 at 22:03

1 Answer 1

0

Well I figured out why it wasn't working! my code was putting in a leading ' but in the cell, it reads it as a "Make this a text entry" so it doesn't show up in the debug.print ..

I changed my code to use an array instead of the cell to hold the string while I build it, and then use the formulaR1C1 line to output to the cell..

For cRow = 9 To row
    For Each WS In Worksheets
        If Left(WS.Name, 5) <> "Total" Then
            If Left(WS.Name, InStr(WS.Name, " ") - 1) = "December" Then
                ytdSheet.Cells(cRow, 2).FormulaR1C1 = "=sum(" & sArr(1) & "'" & WS.Name & "'!R" & cRow & "C2)" 'HERE!!!
                'Debug.Print "=" & ytdSheet.Cells(cRow, 2).Value & "'" & WS.Name & "'!R" & cRow & "C2" 'HERE!!!
            Else
                sArr(1) = sArr(1) & "'" & WS.Name & "'!R" & cRow & "C2, "
                Debug.Print sArr(1)
            End If
        End If
    Next WS
Next cRow

works like a charm!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.