标题说明了一切。请考虑以下示例:
Option Explicit
Sub RoundToDecimalsDefinedByEndUser()
Dim DecimNum As Integer
DecimNum = InputBox("How many decimals do you want?", "Enter")
Cells(1, 1).Value = Application.WorksheetFunction.Round(Cells(1, 1).Value, DecimNum)
End Sub
考虑最终用户想要2个小数的情况,要舍入的数字是0.10111。 结果应为0.10,但Excel强制结果为0.1。关于如何保持尾随零的任何建议?
答案 0 :(得分:3)
在代码行cells(1,1).value...
下方,您可以根据以下内容添加更多代码:
cells(1,1).numberformat...
您使用的数字格式为#,0.0000000
- 不知何故,您需要将零的数量调整为等于DecimNum
dim x as integer
dim numForm as string: numForm = "#,0."
for x = 0 to decimNum
numForm = numForm & "0"
next x
(未测试,因为我在这台机器上没有Excel)
答案 1 :(得分:3)
考虑:
Option Explicit
Sub RoundToDecimalsDefinedByEndUser()
Dim DecimNum As Double, wf As WorksheetFunction
Set wf = Application.WorksheetFunction
DecimNum = InputBox("How many decimals do you want?", "Enter")
With Cells(1, 1)
.Value = wf.Round(.Value, DecimNum)
.NumberFormat = "0." & wf.Rept("0", DecimNum)
End With
End Sub
这会将 A1 作为数值。