我有一个表链接到用户输入ISBN号的表单。我正在检查以确保ISBN有效。但是,当我到达需要比较两个数字的点时,我肯定被告知它们不匹配,当它们肯定匹配时。
Private Sub isbn_BeforeUpdate(Cancel As Integer)
Dim isbn As String
Dim cleanIsbn As Double
Dim onlyIsbn As Double
Dim checkDigit As Integer
Dim legnth As Integer
length = 0
isbn = Forms!frmPubInfo!isbn.Value
' Strip out all hyphens
For i = 1 To Len(isbn)
Dim ch As String
ch = Mid(isbn, i, 1)
If IsNumeric(ch) Then
length = length + 1
Dim num As Integer
num = CInt(ch)
cleanIsbn = (cleanIsbn * 10) + num
End If
Next
' Check if 13 numbers
If length = 13 Then
Dim xBy3 As Boolean
Dim total As Integer
Dim calcCheckDigit As Integer
total = 0
xBy3 = False
' Calculate total amount
For j = 1 To 12
ch = Mid(cleanIsbn, j, 1)
If xBy3 = True Then
total = total + (ch * 3)
xBy3 = False
Else
total = total + ch
xBy3 = True
End If
Next
' Get calculated check digit
calcCheckDigit = 10 - (total Mod 10)
' Extract check digit
checkDigit = Mid(cleanIsbn, 13, 1)
' Debug output
MsgBox ("Actual CheckDigit: " & checkDigit & vbNewLine & _
"Calculated CheckDigit: " & calcCheckDigit)
' Check if check digit and calculated check digit match
If checkDigit <> calculatedCheckDigit Then
MsgBox ("checkDigit and calcCheckDigit are not the same")
Else
MsgBox ("They match! ISBN is good!")
End If
Else
' Display error
MsgBox ("Not enough numbers!")
End If
End Sub
当我开始检查'检查校验位和计算校验位是否匹配'时,If语句总是说它们不匹配,即使上面的调试输出给出了相同的两个数字。
我试过了:
CStr
CInt
。我最初认为这是数据类型的一个问题,但如果我将它们转换为相同的类型,就像我在比较它们一样,这不是问题,对吧?
这都是使用Access 2013。
答案 0 :(得分:3)
男人......我无法相信我一开始并没有看到这一点。我测试了你的代码并得到了与你类似的结果。仔细观察之后,我注意到if语句错了。简而言之,您需要使用Option Explicit
并且此错误将被捕获。 Option Explicit
确保声明所有变量。在没有错误被抛出。
您的语句包含空
If checkDigit <> calculatedCheckDigit Then
你没有名为calculatedCheckDigit
的变量,它应该是calcCheckDigit
。
If checkDigit <> calcCheckDigit Then
只是旁注:您删除连字符的代码显然有效,但我提供了这个调整。
' Dim as string since it is treated as one with Mid anyway.
' In practice Len didnt give accurate results while it was Double.
Dim cleanIsbn As String
' Strip out all hyphens
cleanIsbn = Replace(isbn, "-", "")
' Check if 13 numbers
If (Len(cleanIsbn) = 13) And IsNumeric(cleanIsbn) Then
' Process Stuff
Else
' Display error
MsgBox "Does not appear to be a valid ISBN value!"
End If
获取isbn并使用替换删除连字符。如果结果变为cleanIsbn是13个字符长并且是数字,那么你可以假设它有一个很好的值来处理。
ISBN参考
我不得不查一查,但ISBN编号背后的数字位于参考here