2010-12-08 64 views
1

嗨,我有一個產生12位數字的UPC碼(基於第一11位JavaScript函數:Javascript轉換爲Excel VB功能生成#NUM!錯誤

function ccc12(rawVal) { 
    factor = 3; 
    sum = 0; 
    rawVal = rawVal.toString(); 
    if (rawVal.length!=11){ 
     throw "The UCC-12 ID Number requires that you enter 11 digits."; 
    } 
    for (index = rawVal.length; index > 0; --index) { 
    sum = sum + rawVal.substring (index-1, index) * factor; 
    factor = 4 - factor; 
    } 
    return ((1000 - sum) % 10); 
} 

假設上面如果我給84686400201作爲rawVal,然後2將結果返回。 這是再轉換爲

Function generateUPC(upcCode As Integer) As String 
    Dim upcCheckDigit, factor, sum As Integer 
    Dim upcString As String 
    factor = 3 
    sum = 0 

    For i = Len(upcCode) To 0 Step -1 
     sum = sum + Mid(upcCode, i - 1, 1) * factor 
     factor = 4 - factor 
    Next i 
    upcCheckDigit = ((1000 - sum) Mod 10) 
    upcString = upcCode & upcCheckDigit 

    generateUPC = upcString 
End Function 

該函數返回原始字符串加上一個數字,而是我得到#NUM!在工作表中,當我把= generateUPC(84686400201)進入細胞。

有何想法?從來沒有真正困擾做VB宏等之前,所以這是我新

回答

2

我建議改變upcCode爲一個字符串,以避免溢出,改變Mid函數內的循環和索引,以避免超出界限的錯誤。

Function generateUPC(upcCode as String) As String 
    Dim upcCheckDigit, factor, sum As Integer 
    Dim upcCode, upcString As String 
    factor = 3 
    sum = 0 

    For i = Len(upcCode) To 1 Step -1 
     sum = sum + Mid(upcCode, i, 1) * factor 
     factor = 4 - factor 
    Next i 
    upcCheckDigit = ((1000 - sum) Mod 10) 
    upcString = upcCode & upcCheckDigit 

    generateUPC = upcString 
End Function 
2

VBA整數是-32K至+ 32K

VBA多頭是-2B至+ 2B

你「upcCode」整數大於長數據類型,所以我有雙,這是一個浮動嘗試過,但工作原理:

Function generateUPC(upcCode As Double) As String 
    Dim upcCheckDigit, factor, sum As Double 
    Dim upcString As String 
    factor = 3 
    sum = 0 

    For i = Len(upcCode) To 0 Step -1 
     sum = sum + Mid(upcCode, i - 1, 1) * factor 
     factor = 4 - factor 
    Next i 
    upcCheckDigit = ((1000 - sum) Mod 10) 
    upcString = upcCode & upcCheckDigit 

    generateUPC = upcString 

End Function 
+0

儘管我將第一個答案標記爲正確,但這同樣好。也贊成你指出整數與長期問題的事實。 – CogitoErgoSum 2010-12-08 21:58:01