Last active
July 29, 2021 22:01
-
-
Save cimnine/7913819 to your computer and use it in GitHub Desktop.
Luhn Algorithm in VBA (for example for use in Excel)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
' Version 1.0.0 | |
' You may use these functions directly in Excel: "=luhnCheck(A55)" | |
' probably only needed internally | |
Function luhnSum(InVal As String) As Integer | |
Dim evenSum As Integer | |
Dim oddSum As Integer | |
evenSum = 0 | |
oddSum = 0 | |
Dim strLen As Integer | |
strLen = Len(InVal) | |
Dim i As Integer | |
For i = strLen To 1 Step -1 | |
Dim digit As Integer | |
digit = CInt(Mid(InVal, i, 1)) | |
If ((i Mod 2) = 0) Then | |
oddSum = oddSum + digit | |
Else | |
digit = digit * 2 | |
If (digit > 9) Then | |
digit = digit - 9 | |
End If | |
evenSum = evenSum + digit | |
End If | |
Next i | |
luhnSum = (oddSum + evenSum) | |
End Function | |
' for the curious | |
Function luhnCheckSum(InVal As String) | |
luhnCheckSum = luhnSum(InVal) Mod 10 | |
End Function | |
' true/false check | |
Function luhnCheck(InVal As String) | |
luhnCheck = (luhnSum(InVal) Mod 10) = 0 | |
End Function | |
' returns a number which, appended to the InVal, turns the composed number into a valid luhn number | |
Function luhnNext(InVal As String) | |
Dim luhnCheckSumRes | |
luhnCheckSumRes = luhnCheckSum(InVal) | |
If (luhnCheckSumRes = 0) Then | |
luhnNext = 0 | |
Else | |
luhnNext = ((10 - luhnCheckSumRes)) | |
End If | |
End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The doubling is alternating, so why not just use a flag to alternate. This way it doesn't matter if the length of InVal is even or odd