Validate any PIN or ZIP code VBA (Visual Basic for Applications) code example

Validate any PIN or ZIP code VBA (Visual Basic for Applications) code example

PIN/ZIP

Represents a unique address and validating correct PIN/ZIP always a question mark in VBA. In this article will take you through a simple and dynamic example where user can choose PIN/ZIP code length and validate by removing any special characters.

Code example

Public Function ValidateZIPCode(zipString As String, Optional requiredLen As Integer = 6, Optional isAlphaNumeric As Boolean = False, Optional allowChars As String = "") As String
    ValidateZIPCode = "Zip/Pin Code error"
    On Error GoTo errh
    Dim oZipCode As String
    'zip code string must not be empty
    If zipString <> "" Then
        Dim zipArray() As String
        zipArray = SplitStringIntoArray(zipString)
        
        'Iterate each item
        Dim oChar
        For Each oChar In zipArray
            'Only Numbers
            If isAlphaNumeric = False Then
                If IsNumeric(oChar) = True Then
                    oZipCode = oZipCode & oChar
                End If
            Else 'Alpha numeric
                'Check if number
                If IsNumeric(oChar) = True Then
                    oZipCode = oZipCode & oChar
                Else
                    'Convert to Upper case
                    Dim oStr As String
                    oStr = UCase(oChar)
                    'Loop through each character
                    Dim i As Integer
                    For i = 65 To 90
                        If Asc(oStr) = i Then
                            oZipCode = oZipCode & oStr
                            Exit For
                        End If
                    Next i
                End If
            End If
        Next oChar
    End If
    
    'Check zip code length
    If Len(oZipCode) > requiredLen Then
        ValidateZIPCode = Mid(oZipCode, 1, requiredLen)
    ElseIf Len(oZipCode) = requiredLen Then
        ValidateZIPCode = oZipCode
    End If
    
errh:
    If Err.Number <> 0 Then
        Debug.Print Err.Description
    End If
End Function

Supported Function

Function SplitStringIntoArray(ByVal value As String)
    value = StrConv(value, vbUnicode)
    SplitStringIntoArray = Split(Left(value, Len(value) - 1), vbNullChar)
End Function

Parameters

  1. zipString: Required string parameter, which refers to Zop code which user wants to be validated
  2. requiredLen: Optional Integer parameter, which indicates what length of output user should get back from the function the default is 6 digits
  3. isAlphaNumeric: Optional Boolean parameter, determines if supplied zip code is in Alpha Numeric format. The default is Numeric
  4. allowChars: Optional String parameter, skips given special characters during validation. Default is empty string

Output

Leave a Reply

Your email address will not be published. Required fields are marked *