Excel/Round VBA

Advertisement


Question
I used this code to create a macro to round numbers:

Sub RoundCells()
   Dim c As Range
   For Each c In Selection.Cells
   c.Formula = "=ROUND(" & Right(c.Formula, Len(c.Formula) - 1) & ",0)"
   Selection.NumberFormat = "_(* #,##0_);_(* (#,##0);_(*   ""-""_);_(@_)"
   Next
End Sub

It works great for rounding positive and negative numbers with a forumula in the cell, but if I try to use this code to round a cell with a number value in it (no formula), the negatives turn into positives.  Any advice?

Answer
Hi SK,

Something like this:

Sub RoundCells()
   Dim c As Range
   For Each c In Selection.Cells
       If c.HasFormula Then
         c.Formula = "=ROUND(" & Right(c.Formula, Len(c.Formula) - 1) & ",0)"
       Else
         c.Formula = "=ROUND(" & Right(c.Formula, Len(c.Formula)) & ",0)"
       End If
   Next
   Selection.NumberFormat = "_(* #,##0_);_(* (#,##0);_(*   ""-""_);_(@_)"
End Sub
About Excel
This topic answers questions related to Microsoft Excel spreadsheet (or workbook) stand-alone or Mircrosoft Office Excel including Excel 2003, Excel 2007, Office 2000, and Office XP. You can get Excel help on Excel formulas(or functions), Excell macros, charting in Excel, advanced features, and the general use of Excel. This does not provide a general Excel tutorial nor the basics of using a spreadsheet. It provides specific answers to using Microsoft Excel only. If you do not see your Excel question answered in this area then please ask an Excel question here

Excel

All Answers


Answers by Expert:


Ask Experts

Volunteer


Jan Karel Pieterse

Expertise

Excel and Excel/VBA questions

Experience

Excel MVP

Organizations
Self employed Excel developer

Education/Credentials
Bachelor in Chemical Engineering

Awards and Honors
Microsoft MVP award since 2002

Past/Present Clients
Shell, Fortis bank, ABN-AMRO bank, Morgan Stanley, ...

©2016 About.com. All rights reserved.