2015-07-28 42 views
1

我有一個Excel工作表,其中我有幾列和一列是Amount我必須驗證每個單元格並檢查它的長度在小數點後是否大於2,如果是,則拋出錯誤。獲取小數位數的長度

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 

回答

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

+0

'num'?我希望它應該是'n'? –

+0

沒有問題的朋友!讓我試試看!然後我認爲我不需要'itg'在這裏吧? –

+0

美!完善!!接下來的4分鐘!用這個把我的頭一整天砸了.. :)這種方法有沒有什麼缺點?我的意思是它會忽略任何類型的價值,如你的知識! –

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 
+0

它會處理沒有小數點的值嗎? –

+1

用我的魔法編輯魔杖輕微的波浪,是的。 –

+0

您的更新效果很好!感謝您的時間.. :) –