An experiment in applied Excel formulas

As an exercise, I developed a set of routines that lets you apply a formula to a group of target cells. Actually, it's because I couldn't find anything similar anywhere else. It's ready to be made into an add-in, but currently it only works on formulas with one parameter (i.e. PROPER, AVERAGE, SUM, CLEAN, etc).

For example, if you have a group of cells with a given formula or value, and you want to change them to match the value of another cell, it's a tedious process to edit each one and change them. I find this to be a common problem.

For example, if you have ten cells (with or without formulas) and have another cell with the SUM formula, you can use this code to apply the SUM formula to those ten cells in a few short steps.

Screenshot

Apply Formulas

To get the formula from the source cell, I wrote the following function:

Function GetCellFormula(sourceCellValue As String) As String
' returns formula from cell
  GetCellFormula = Mid$(sourceCellValue, 2, _
    WorksheetFunction.Find("(", sourceCellValue) - 2)
End Function

To return a Range Object, I encapsulated the usual method:

Function GetRange(strRange As String) As Excel.Range
  On Error Resume Next
  GetRange = Excel.Range(strRange)
  ' if above fails, GetRange will = Nothing
End Function

And I even went ahead and broke one of my own rules about looping. Here's how I update the target cells with the source formula:

  ' apply formula to each target cell
  For Each cell In targetRng
  targetCellContents = Right$(cell.Formula, Len(cell.Formula) - 1)
  cell.Formula = "=" & sourceFormula & "(" & targetCellContents & ")"
  Next cell

Download sample workbook

Related Articles:

About JP

I'm just an average guy who writes VBA code for a living. This is my personal blog. Excel and Outlook are my thing, with a sprinkle of Access and Word here and there. Follow this space to learn more about VBA. Keep Reading »

Share This Article:

Share and bookmark this articledelicious buttonfacebook buttonlinkedin buttonstumbleupon buttontwitter button

comment bubble 1 Comment:

  1. Jon Peltier writes:

    Looping's not a sin if it's the only way to get something done. If each cell has a distinct formula, then it's the only (reliable) way.

Comments on this article are closed. Why?

Site last updated: February 12, 2012