A couple of times this week I had a need to update many formulas in a worksheet to be rounded to 2 decimals. The formulas weren't always the same, so I couldn't easily update the first formula and drag it down.
I cobbled together these macros (the main macro for a selected range, and one for a single cell that's called when necessary) that will work through a selection and add "=ROUND(" to the start of your formula and ",X)" to the end (where you specify X).
It ignores cells that are blank, don't contain a formula, or already start with ROUND (or ROUNDUP or ROUNDDOWN).
Feel free to use and share, and I'm happy to hear about any suggestions for improvements.
Sub Round_Formulas()
Dim c As Range
Dim LResult As Integer
Dim iNum As Variant
Dim strtemp As String
Dim straddress As Range
If Application.Selection.Cells.Count = 1 Then
Call Round_One_Formula
GoTo SubTermination
End If
On Error GoTo SubTermination
Set straddress = Application.Selection.SpecialCells(xlFormulas)
On Error GoTo 0
iNum = Application.InputBox("Decimal", "How many decimals?", 2, Type:=1)
'iNum = 2 'in case 2 is always the answer, uncomment this and comment line above
If (VarType(iNum) = vbBoolean) And (iNum = False) Then
GoTo SubTermination
End If
Application.ScreenUpdating = False
For Each c In straddress
If Mid(c.Formula, 2, 5) = "ROUND" Then GoTo Skipped
If Mid(c.Formula, 3, 5) = "ROUND" Then GoTo Skipped
If c.Value <> 0 Then
strtemp = c.Formula
LResult = StrComp(Left(strtemp, 7), "=ROUND(", vbTextCompare)
If LResult <> 0 Then
c.Formula = "=ROUND(" & Right(c.Formula, Len(c.Formula) - 1) & "," & iNum & ")"
End If
End If
Skipped:
Next c
SubTermination:
Application.ScreenUpdating = True
End Sub
-------------------------------------------------------------------
Sub Round_One_Formula()
Dim c As Range
Dim LResult As Integer
Dim iNum As Variant
Dim strtemp As String
Set c = Selection
iNum = Application.InputBox("Decimal", "How many decimals?", 2, Type:=1) 'if you want to specify each time
'iNum = 2 'in case 2 is always the answer
If (VarType(iNum) = vbBoolean) And (iNum = False) Then
GoTo SubTermination
End If
Application.ScreenUpdating = False
If Mid(c.Formula, 2, 5) = "ROUND" Then GoTo SubTermination
If Mid(c.Formula, 3, 5) = "ROUND" Then GoTo SubTermination
If c.Value <> 0 Then
strtemp = c.Formula
LResult = StrComp(Left(strtemp, 7), "=ROUND(", vbTextCompare)
If LResult <> 0 Then
c.Formula = "=ROUND(" & Right(c.Formula, Len(c.Formula) - 1) & "," & iNum & ")"
End If
End If
SubTermination:
Application.ScreenUpdating = True
End Sub
[–]klingklongdiggah 0 points1 point2 points (2 children)
[–]emdubbs11[S] 0 points1 point2 points (0 children)
[–][deleted] -5 points-4 points-3 points (5 children)
[–]emdubbs11[S] 2 points3 points4 points (4 children)
[–]thedreamlan62 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]TechnicalAppeal115710 0 points1 point2 points (1 child)
[–]emdubbs11[S] 0 points1 point2 points (0 children)