Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round to 2 decimal places in VBA?

Tags:

excel

vba

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)
like image 678
Anthony Avatar asked Nov 01 '18 10:11

Anthony


People also ask

How do you round decimals in VBA?

VBA Round function uses “round to even” logic. If the number you are trying to round has the last digit after decimal >= 0.6, VBA Round function rounds it up (Round UP). If the number you are trying to round have the last digit after decimal <= 0.4, it rounds it down (Round Down).

How do you round to 2 decimal places in Excel?

For example: If you wanted to use the number from cell A2 and have it rounded to two decimal places, you could enter =ROUND(A2,2). Or, if you want to divide cell B2 by cell C2, and round the result to 3 decimals, you would use =ROUND(B2/C2,3).


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)
like image 153
Wizhi Avatar answered Sep 22 '22 10:09

Wizhi