Insert formula into multiple cells in Excel Spreadsheet, via VBA
Posted on 2011-09-08
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
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?