VBA If语句返回错误的值



我正在自动化一个脚本,将检查数字应用于一系列字段。在这样做的过程中,我有它的大部分设置,并有它的工作没有问题,现在它又起作用了。我希望你能再给我一次审阅。

我一直在用以下号码测试: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。

任何帮助都将非常感激。

最好,约翰

Dim n, w, p, c, cp As Long
Dim x, y, r As Integer

上面的声明不是你想要的。cp将是一个Long,r将是一个Integer,但所有其他变量将是variables。

这导致c = x + y作为字符串串联执行,因为xy是在变体中包装的字符串。

不要使用Len()函数:对于字符串,它返回字符的数量,但对于其他类型,它返回内部的东西。因此,我建议您先将参数转换为字符串:

If Len(CStr(p)) = 2 Then

这里有一些关于你的代码的建议。

首先,使用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

这些更改就绪后,将返回正确的结果。

最新更新