Wednesday, July 14, 2010

Format a credit card number

Function FormatCreditCard(ByVal text As String) As String
    Dim i As Long
    
    ' ignore empty strings
    If Len(text) = 0 Then Exit Function
    
    ' get rid of dashes, spaces and invalid chars
    For i = Len(text) To 1 Step -1
        If InStr("0123456789", Mid$(text, i, 1)) = 0 Then
            text = Left$(text, i - 1) & Mid$(text, i + 1)
        End If
    Next
    ' then, re-insert them in the correct position
    FormatCreditCard = Format$(text, "!@@@@ @@@@ @@@@ @@@@")
    
End Function

Francesco Balena