如何在VBA中四舍五入

时间:2019-05-20 01:19:23

标签: vba

我正在使用worksheetFunction.pmt,并且需要将msgbox中的输出舍入到小数点后两位或仅显示整数。

我已将变量声明为Double并尝试将Round添加到msgbox输出中,但遇到运行时错误13。我不知道将Round函数放在哪里


Sub pmt()
Dim Sum, Rate, Period As Double
Sum = InputBox("Enter the sum of the loan")
Rate = InputBox("Enter the interest rate")
Period = InputBox("Enter the number of payments")
MsgBox "Your PMT is: $ " & WorksheetFunction.pmt(Rate, Period, -Sum) & ""
End Sub

我希望结果仅返回2个小数位。是否可以舍入worksheetFunction.pmt

1 个答案:

答案 0 :(得分:1)

只需使用VBA Round函数:

Sub pmt()
'Take care when naming your variables
'Dim dlbSum as Double, dblRate as Double, dblPeriod as Double
'Defining Period as Dboule doesn't make sense anyway
Dim Sum, Rate, Period As Double

Sum = InputBox("Enter the sum of the loan")

'You should consider error checking, entering the percentage symbol will create an error in the calculations
Rate = InputBox("Enter the interest rate")

Period = InputBox("Enter the number of payments")

MsgBox "Your PMT is: $ " & Round(WorksheetFunction.pmt(Rate, Period, -Sum), 2) & ""
End Sub