How to round to 2 decimal places in VBA?

Viewed 56494

In cell B2 I have variable with the value 297.123 before doing calculations In VBA I would like to round this to 297.12. See the code below as to what I have tried. Both have evaluated fuel to 297. What am I doing wrong?

Dim fuel As Integer
Dim linecount As Long

linecount2 = 2

fuel = Format(ws.Cells(linecount2, 2), "0.00")
fuel = Round(ws.Cells(linecount2, 2), 2)
1 Answers

Change Dim fuel As Long -> Dim fuel As Double

And both of your formula will work.

Dim fuel As Double
Dim linecount2 As Long
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")


linecount2 = 2

fuel = Format(ws.Cells(linecount2, 2), "0.00")
fuel = Round(ws.Cells(linecount2, 2), 2)
fuel = WorksheetFunction.Round(ws.Cells(linecount2, 2), 2) '@suggested by T.M.


MsgBox "try"

End Sub
  • Dim Long is for Integers (whole numbers)
  • Dim Double is for numbers with decimal points (can store more decimal points, up to 15 digits)
  • Dim Single is for numbers with decimal points (store less decimal points, up to 7 digits)
Related