This allows you to calculate the Luhn checksum for a string of decimal digits, as well as to validate that checksum. Here's the code.
Just paste that code in a module and the functions will be accessible from anywhere else in your code. The functions are used as follows.
Luhn() calculates the Luhn checksum from a string of decimal digits, and outputs that checksum as a byte.
LuhnAppend() calculates the Luhn checksum from a string of decimal digits, and outputs a string that contains the original string with the checksum digit appended to it.
LuhnValidate() takes a complete decimal string including the checksum digit, and validates it. The output is boolean (True or False)
LuhnValidateSeparate() takes a decimal string without the checksum digit, and validates it against a separately provided byte that contains the checksum digit. The output is Boolean.
The Luhn calculation function ignores common separators found in decimal digit strings that typically use the Luhn checksum (such as those on credit cards). These separators are spaces and dashes.
Code:
Public Function Luhn(ByVal DecimalString As String) As Byte
Dim x As Long
Dim y As Long
Dim temp As String
Dim n As Long
If InStr(1, DecimalString, "-") Then
DecimalString = Replace("DecimalString", "-", "")
ElseIf InStr(1, DecimalString, " ") Then
DecimalString = Replace("DecimalString", " ", "")
End If
n = 1
For x = Len(DecimalString) To 1 Step -1
temp = CLng(Mid$(DecimalString, x, 1)) * ((n And 1) + 1)
If Len(temp) = 2 Then
y = y + CLng(Mid$(temp, 1, 1)) + CLng(Mid$(temp, 2, 1))
Else
y = y + CLng(temp)
End If
n = n + 1
Next x
Luhn = (10 - (y Mod 10)) Mod 10
End Function
Public Function LuhnAppend(ByVal DecimalString As String) As String
LuhnAppend = DecimalString & CStr(Luhn(DecimalString))
End Function
Public Function LuhnValidate(ByVal DecimalString As String) As Boolean
LuhnValidate = (Luhn(Left$(DecimalString, Len(DecimalString) - 1)) = CByte(Right$(DecimalString, 1)))
End Function
Public Function LuhnValidateSeparate(ByVal DecimalString As String, ByVal Checksum As Byte) As Boolean
LuhnValidateSeparate = (Luhn(DecimalString) = Checksum)
End Function
Luhn() calculates the Luhn checksum from a string of decimal digits, and outputs that checksum as a byte.
LuhnAppend() calculates the Luhn checksum from a string of decimal digits, and outputs a string that contains the original string with the checksum digit appended to it.
LuhnValidate() takes a complete decimal string including the checksum digit, and validates it. The output is boolean (True or False)
LuhnValidateSeparate() takes a decimal string without the checksum digit, and validates it against a separately provided byte that contains the checksum digit. The output is Boolean.
The Luhn calculation function ignores common separators found in decimal digit strings that typically use the Luhn checksum (such as those on credit cards). These separators are spaces and dashes.