Excel VBAでJANのCDをチェック

こんなコードの需要がどれくらいあるかわかりませんが、必要があればどうぞ。シートで普通に=JAN.Validate(A1)とかやればいいです。

Option Explicit

Public Function Validate(JAN As String) As Boolean
    Select Case Len(JAN)
    Case 8, 13
        Validate = (CalculateCD(JAN) = Int(Right(JAN, 1)))
    Case Else
        'Raise
        Validate = False
    End Select
End Function

Public Function CalculateCD(JAN As String) As Integer
    Select Case Len(JAN)
    Case 7, 8
        CalculateCD = CalculateCD8(JAN)
    Case 12, 13
        CalculateCD = CalculateCD13(JAN)
    Case Else
        'Raise
        Exit Function
    End Select
End Function

Private Function CalculateCD8(JAN As String) As Integer
    Dim cksum As Integer
    Dim i As Integer
    For i = 1 To 7 Step 2
        cksum = cksum + Int(Mid(JAN, i, 1)) * 3
    Next i
    For i = 2 To 6 Step 2
        cksum = cksum + Int(Mid(JAN, i, 1))
    Next i

    CalculateCD8 = (10 - (Int(Right(cksum, 1)) Mod 10)) Mod 10
End Function

Private Function CalculateCD13(JAN As String) As Integer
    Dim cksum As Integer
    Dim i As Integer
    For i = 1 To 11 Step 2
        cksum = cksum + Int(Mid(JAN, i, 1))
    Next i
    For i = 2 To 12 Step 2
        cksum = cksum + Int(Mid(JAN, i, 1)) * 3
    Next i

    CalculateCD13 = (10 - (Int(Right(cksum, 1)) Mod 10)) Mod 10
End Function
Posted on

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です


*

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>