Add "Round" to each formula in selection

User avatar
VegasNath
5StarLounger
Posts: 1185
Joined: 24 Jan 2010, 12:02
Location: Wales, UK.

Add "Round" to each formula in selection

Post by VegasNath »

In a similar fashion to this post, would it be possible convert all formulas in a selection to include the 'Round' function to n decimal places. Ideally, I would like maybe an input box so the user can dictate the amount of decimals required.
Last edited by HansV on 10 Aug 2010, 19:06, edited 1 time in total.
Reason: to correct link to post
:wales: Nathan :uk:
There's no place like home.....

User avatar
HansV
Administrator
Posts: 78488
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Add "Round" to each formula in selection

Post by HansV »

This version will work OK if you
- Select more than one cell.
- At least one cell within the selection has a formula.
- You don't have multiple cells with a single array formula (single cells with array formulas are OK).

Code: Select all

Sub AddRound()
  Dim rng As Range
  Dim strFormula As String
  Dim n As Integer
  n = InputBox("To how many decimals do you want to round?")
  ' Loop through cells with formulas
  For Each rng In Selection.SpecialCells(xlCellTypeFormulas)
    ' Formula without =
    strFormula = Mid(rng.Formula, 2)
    ' New formula
    strFormula = "=ROUND(" & strFormula & "," & n & ")"
    ' Check for array formula
    If rng.HasArray Then
      ' Apply new formula to all cells that have this array formula
      rng.CurrentArray.FormulaArray = strFormula
    Else
      ' Apply new formula
      rng.Formula = strFormula
    End If
  Next rng
End Sub
Best wishes,
Hans

User avatar
VegasNath
5StarLounger
Posts: 1185
Joined: 24 Jan 2010, 12:02
Location: Wales, UK.

Re: Add "Round" to each formula in selection

Post by VegasNath »

Thanks a lot Hans, much appreciated. :cheers:
:wales: Nathan :uk:
There's no place like home.....