vba excel表格中文本框中的小数点处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8751025/
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
Decimal points handling within textbox in an excel form
提问by macutan
I want to display a number in a textbox within an excel form. report, however I only want to show any decimal points if they are present and the I only want to show 2 decimal places.
我想在 Excel 表单的文本框中显示一个数字。报告,但是我只想显示任何存在的小数点,并且我只想显示 2 个小数位。
e.g. if the number is 12 then I want to show 12
例如,如果数字是 12,那么我想显示 12
If the number is 12.1 then I want to show 12.10
如果数字是 12.1 那么我想显示 12.10
If the number is 12.126 then I want to show 12.13
如果数字是 12.126 那么我想显示 12.13
At the moment i have the below code and it is not showing me decimal points:
目前我有以下代码,但没有显示小数点:
Me.Amount.Value = Format(Me.Amount, "#,###")
采纳答案by phoog
You could write a function to conditionally return one of two format strings:
您可以编写一个函数来有条件地返回两种格式字符串之一:
Function GetFormatString(varValue As Variant) As String
Dim dblValue As Double
If IsNumeric(varValue) Then
dblValue = CDbl(varValue)
If dblValue = Int(dblValue) Then
GetFormatString = "#,###"
Else
GetFormatString = "#,###.00"
End If
End If
End Function
Private Sub Amount_AfterUpdate()
Dim strFormat As String
strFormat = GetFormatString(Me.Amount.Value)
Me.Amount.Value = Format(Me.Amount.Value, strFormat)
End Sub