Option Compare Database
Option Explicit
Public Function ParseUSPhone(ByRef strPotentialPhone As String, ByVal DisplayStore As String) As String
On Error GoTo errHandler
Dim intPhoneLength As Integer
Dim strParsedPhone As String
' This constant contains punctuation and characters
' that should be filtered from the input string, leaving only digits.
Const CHARS = ".!?,;:""'()[]{}-.abcdefghijklmnopqrstuvwxyz"
Dim intIndex As Integer
strParsedPhone = strPotentialPhone
strPotentialPhone = Trim(Replace(strPotentialPhone, _
vbTab, " "))
For intIndex = 1 To Len(CHARS)
strPotentialPhone = Trim(Replace(strPotentialPhone, _
Mid(CHARS, intIndex, 1), " "))
Next intIndex
Do While InStr(strPotentialPhone, " ")
strPotentialPhone = Replace(strPotentialPhone, _
" ", "")
Loop
ParseUSPhone = strPotentialPhone
If DisplayStore = "Display" Then 'should the phone be saved with the display formatting
intPhoneLength = Len(strPotentialPhone)
Select Case intPhoneLength
Case 0
ParseUSPhone = ""
Case 7 ' exchange and number is okay
ParseUSPhone = Format(strPotentialPhone, "@@@-@@@@")
Case 10
ParseUSPhone = Format(strPotentialPhone, "(@@@) @@@-@@@@")
End Select
End If
Cleanup:
Exit Function
errHandler:
'Replace my error handler with your own version
Call GlblErrMsg( _
sFrm:=Application.VBE.ActiveCodePane.CodeModule, _
sCtl:="ParseUSPhone" _
)
Resume Cleanup
Resume
End Function
Public Function ValidateUSPhone(strPotentialPhone) As Boolean
On Error GoTo errHandler
' This constant contains punctuation and characters
' that should be filtered from the input string, leaving only digits.
Const CHARS = ".!?,;:""'()[]{}-.abcdefghijklmnopqrstuvwxyz"
Dim intIndex As Integer
Dim intPhoneLength As Integer
Dim strParsedPhone As String
strParsedPhone = strPotentialPhone
ValidateUSPhone = False
strPotentialPhone = Trim(Replace(strPotentialPhone, _
vbTab, " "))
For intIndex = 1 To Len(CHARS)
strPotentialPhone = Trim(Replace(strPotentialPhone, _
Mid(CHARS, intIndex, 1), " "))
Next intIndex
Do While InStr(strPotentialPhone, " ")
strPotentialPhone = Replace(strPotentialPhone, _
" ", "")
Loop
intPhoneLength = Len(strPotentialPhone)
Select Case intPhoneLength
Case 0
If strPotentialPhone = strParsedPhone Then
ValidateUSPhone = True
Else
MsgBox Prompt:="Phone numbers must be formatted as either ""(222) 333-444"" or ""555-6666""", buttons:=vbOKOnly, Title:= "Invalid Phone Number"
End If
Case 7 ' exchange and number is okay
ValidateUSPhone = True
Case 10 ' exchange and number is okay
ValidateUSPhone = True
Case Else 'any other length is invalid
MsgBox Prompt:="Phone numbers must be formatted as either ""(222) 333-444"" or ""555-6666""", buttons:=vbOKOnly, Title:= "Invalid Phone Number"
End Select
Cleanup:
Exit Function
errHandler:
' replace with your own error handler
Call GlblErrMsg( _
sFrm:=Application.VBE.ActiveCodePane.CodeModule, _
sCtl:="ValidateUSPhone" _
)
Resume Cleanup
Resume
End Function