我正在致力于自動化腳本以將校驗位應用于一系列欄位。在這樣做時,我已經完成了大部分設定,并且可以正常作業,現在又可以正常作業了。我希望我可以對所有內容進行第二次審查。
我一直在使用以下號碼進行測驗:00276933863801021
正確的校驗位是 6
Function ChkDgt(ByVal Scanline As String)
Dim n, w, p, c, cp As Long
Dim x, y, r As Integer
'Checks for Spaces in Scanline and removes them
Scanline = Replace(Scanline, " ", "", 1, , vbBinaryCompare)
'Determine number of characters in series
For i = 1 To Len(Scanline)
'Determines character being processed
n = Mid$(Scanline, i, 1)
'Defines the weighted value based on odd/even number position
If i Mod 2 = 1 Then
w = 2
Else: w = 1
End If
'multiplies character(number) by weighted value
p = n * w
'All numbers must be between 0 and 9. This checks for 2 digits and adds the two together ex. (16 => 1 6 = 7)
If Len(p) = 2 Then
x = Left(p, 1)
y = Right(p, 1)
c = x y
Else: c = p
End If
'Sums all character products
cp = cp c
Next
'Returns the remainder value of the final sum
r = cp Mod 10
'10 - remainder value equals the check digit
chk = 10 - r
'Returns the Check Digit
ChkDgt = CStr(chk)
End Function
在查看 Len(p) 以確定 2 個值/字符時,這就是我丟失數字并獲得錯誤校驗位的地方。
If Len(p) = 2 Then
x = Left(p, 1)
y = Right(p, 1)
c = x y
Else: c = p
End If
當計數器上的 i = 5 時,乘積應該是 12,轉換為 3,但它保持為 12。
任何幫助將非常感激。
最好的,約翰
uj5u.com熱心網友回復:
Dim n, w, p, c, cp As Long
Dim x, y, r As Integer
上面的宣告不是你想要的。cp將是 Long,r將是 Integer,但所有其他變數都將是 Variants。
這導致c = x y作為字串連接執行,因為x和y是包含在 Variant 中的字串。
uj5u.com熱心網友回復:
與Len()函式保持一致:對于字串,它回傳字符數,但對于其他型別,它回傳內部的內容。因此,我建議您先將引數轉換為字串:
If Len(CStr(p)) = 2 Then
uj5u.com熱心網友回復:
以下是針對您的代碼的幾項建議。
首先,使用Option Explicit。這將允許編譯器標記未定義的變數,這將在某些時候為您省去麻煩。
其次,正確定義變數。如果沒有明確定義型別,變數將被宣告為 Variant。所以在這種情況下:
Dim n As Long, w As Long, p As Long, c As Long, cp As Long
Dim chk As Integer, i As Integer, x As Integer, y As Integer, r As Integer
第三,正確定義你的函式。函式應該回傳一個值。如果未指定,則回傳 Variant。所以在這種情況下:
Function ChkDgt(ByVal Scanline As String) As String
第四,將有問題的代碼塊更改為:
'All numbers must be between 0 and 9. This checks for 2 digits and adds the two together ex. (16 => 1 6 = 7)
If p > 9 Then
x = Left(p, 1)
y = Right(p, 1)
c = x y
Else
c = p
End If
進行這些更改后,將回傳正確的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/329457.html
