I'm trying to figure out the best way to insert a similar formula into multiple columns within a spreadsheet, via VBA.

Disclaimer: I'm an Access developer, branching out into Excel.

My client would like some code that will review a worksheet, compare values in that worksheet to another worksheet in the same workbook, and insert rows and columns as necessary (I have this part working). But the cell in the 2nd row of each column contains a formula that checks to see whether the Sum() of all the values from the 4th row through the Nth row (determined at runtime) is zero. If so, the returned value is an empty string, if not, the returned value is "Out of Balance". I don't have the exact syntax with me, but I beleive it looks like:

=IF(Sum(C4:C400) = 0, "", "Out of Balance")

They then have the conditional formatting set to display that cell in yellow if "Out of Balance".

What is the best way to refer to these cell ranges as I loop through the columns and set both the formula and the conditional formatting? I was working with something along the lines of:

intCol = 3

While ActiveSheet.Cells(3, intCol) <> ""

strFormula = "=IF(Sum(C4:C400) = 0, """", ""Out of Balance"")"

ActiveSheet.Cells(2, intCol).FormulaR1C1 = strFormula

intCol = intCol + 1

Wend

But I'm not sure what the best way is to establish the range (column letter and start/end row) when this worksheet will grow both horizontally and vertically. What is the best method for referencing the "C4:C400" piece of this?

Set fRange = sht.Cells.Find(what:="*", LookIn:=xlFormulas, searchdirection:=xlPreviou

If fRange Is Nothing Then Exit Sub ' otherwise, its an empty worksheet

maxRow = fRange.Row

See attached revised code using this for maxRow. See shaded yellow cell - that column has more rows, and all formulas index their last row the same way as fRange.Row.

Open in new window

Note, this code should really be in a public module. I've done that in the attached.

Cheers,

dave

sumFormula-r4.xls