How do you set the number of decimal places of a value returned in a msgbox after doing a simple calculation in VBA excel 2010

StackOverflow https://stackoverflow.com/questions/16682281

  •  30-05-2022
  •  | 
  •  

Question

im currently using a simple msgbox calc to return a calculated value. How can i restrict the number of decimal places shown in the returned value in the answer msgbox.

here is the script!

Sub CalcmsgboxHect()
    On Error Resume Next
    num = InputBox("Please Enter The Number Of Acres You Would Like To Calculate Into Hectares ")
    MsgBox num * 0.404686 & " Is the Number Of Hectares."
End Sub
Was it helpful?

Solution

Here you go. This applies a format with two decimal places and a thousands separator:

EDIT: Wrapped in an IF to skip if num = 0.

Sub CalcmsgboxHect()
Dim num As Double

num = Application.InputBox(prompt:="Please Enter The Number Of Acres You Would Like To Calculate Into Hectares ", Type:=1)
If num <> 0 Then
    MsgBox Format(num * 0.404686, "#,##0.00") & " Is the Number Of Hectares."
End If
End Sub

As a bonus I declared num as a Double (depite your reckless moniker). Also, I used Application.Inputbox, which allow you to specify and input type. An input type of 1 means the user has to enter a number. This might allow you to get rid of the On Error Resume Next line.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top