获取小数位的长度

时间:2015-07-28 10:14:44

标签: excel vba excel-vba

我有一个Excel工作表,其中我有几列,一列是Amount我要验证每个单元格并检查小数点后的长度是否大于2,如果是,则抛出错误。< / p>

Public Function CheckLength(value As String) As Integer
    Dim n As Double
    Dim itg As Integer
    Dim dcm As Double
    n = value 'Say Value is 50.01 here 
    itg = Int(n) 'Will be 50
    dcm = Split(n - itg, ".")(1) 'But n-itg will yield something and dcm`s value will be 
    '1000001 some strange value where as it has to be `01` or say whatever comes after decimal part
    CheckLength = Len(dcm)
End Function

2 个答案:

答案 0 :(得分:1)

你可以这样做:

Public Function CheckLength(value As String) As Integer
    Dim n As Double
    Dim itg As Integer
    Dim dcm As Double
    n = value
    itg = Int(n)
    dcm = Len(CStr(n)) - InStr(CStr(n), ".")

    CheckLength = dcm
End Function

注意:如果n中没有".",它将返回总长度(因为它将是Len(CStr(n)) - 0),因此您可以检查字符串之前是否包含".",或者您可以检查dcm是否与Len(CStr(n))相同,然后返回0

答案 1 :(得分:1)

如果您确实在检查数字,那么这将有效:

Function CheckLength(value As Double) As Integer
    If InStr(CStr(value), ".") Then
        CheckLength = Len(Split(CStr(value), ".")(1))
    Else
       CheckLength = 0
    End If
End Function

它将数字转换为字符串,使用"."作为分隔符将其拆分,然后返回返回的数组中第二项的长度(这是"."之后的任何内容)

Const myNumber As Double = 50.13245
Debug.Print CheckLength(myNumber) '// Returns 5

'// Split 50.13245 on "." returns an array with 2 parts:
'//    (0) = "50"
'//    (1) = "13245"
'//    Length of (1) '13245' = 5