• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

VBA: formula calculation on dynamic range

Hi there,

I have a pretty large macro that I run to validate the accuracy of data in a file. Right now the code has 100 + formulas referencing static ranges and performing calculations. The only problem is as the file grows in size with time, these formulas will need to reference the entire data range.

What is the trick to use variable ranges within a formula?

Is this close:

Code:
 Range("B10").FormulaR1C1 = "=SUM(Range(startRow & startCol & ":" & endRow & endCol))"
 
Try this
Code:
Range("B10").Formula = "=SUM(" & Range(Cells(startRow, startCol), Cells(endRow, endCol)).Address & ")"
 
No idea about how you get startCol/endCol though.

My guess
Code:
Range("B10").Formula = "=SUM(" & cells(startRow,startCol).address & ":" & cells(endRow,endCol).address & ")"
 
Hi ,

My 2 cents :
Code:
Public Sub temp()
          Dim rangeParameter As Range
          Dim startRow As Long, endRow As Long
          Dim startCol As String, endCol As String

          startRow = 10
          startCol = "F"

          endRow = 77
          endCol = "J"

          Range("B10").Formula = "=SUM(" & startCol & startRow & ":" & endCol & endRow & ")"

          Set rangeParameter = Range(startCol & startRow & ":" & endCol & endRow)
          With rangeParameter
                Range("B11").Formula = "=SUM(" & .Address(1, 1) & ")"
                Range("B12").Formula = "=SUM(" & .Address(1, 0) & ")"
                Range("B13").Formula = "=SUM(" & .Address(0, 1) & ")"
                Range("B14").Formula = "=SUM(" & .Address(0, 0) & ")"
          End With
End Sub
Narayan
 
Hi Jeffrey ,

All that has been done is to present 2 different ways of coding the same formula ; in the first statement , the formula is coded using the row and column numbers , while in the second statement , the variable rangeparameter is a variable of type Range , which is set to the desired worksheet reference. Now , to use this in the formula , we need to include its address.

Basically , when you want to insert a formula using VBA , it has to be a string ; either this string is hard-coded into the statement , or it is derived using the Address property of a Range variable.

Narayan
 
Back
Top