vba 在VBA excel 2010中进行简单计算后,如何设置msgbox中返回值的小数位数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16682281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:14:10  来源:igfitidea点击:

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

vbadecimal-pointmsgbox

提问by Adrian Gornall

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.

我目前使用一个简单的 msgbox calc 来返回一个计算值。我如何限制答案 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

回答by Doug Glancy

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.

编辑:如果 num = 0,则包裹在 IF 中以跳过。

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 numas a Double(depite your reckless moniker). Also, I used Application.Inputbox, which allow you to specify and input type. An input type of 1means the user has to enter a number. This might allow you to get rid of the On Error Resume Nextline.

作为奖励,我宣布numDouble(尽管你鲁莽的绰号)。另外,我使用了Application.Inputbox,它允许您指定和输入类型。输入类型1意味着用户必须输入一个数字。这可能会让你摆脱这On Error Resume Next条线。