Blog Home  Home Feed your aggregator (RSS 2.0)  
U R MY.Net - VB.Net Format Phone Number Function
My Tips, Tricks and References
 
 Friday, January 26, 2007

Here is a function to format phone numbers. I picked it up from here: http://www.freevbcode.com/ShowCode.asp?ID=1968

'Takes any entered phone number and returns it in ###-#### format
'or (###) ###-####

Public Function FormatPhoneNumber(ByVal sNumToBeFormatted As _
   String) As String

Dim iNumberLength As Integer 'Used for the Phone Number length
  
'Trim any leading and trailing spaces

sNumToBeFormatted = Trim$(sNumToBeFormatted)
  
'Length of the phone number.

iNumberLength = Len(sNumToBeFormatted)
  
Select Case iNumberLength

  Case 7  'Format : #######

    FormatPhoneNumber = Left$(sNumToBeFormatted, 3) & _
        "-" & Right$(sNumToBeFormatted, 4)
    Exit Function

  Case 8  'Format : ###-#### or ### ####

    If Mid$(sNumToBeFormatted, 4, 1) = "-" Then
       FormatPhoneNumber = sNumToBeFormatted
       Exit Function
    Else
       FormatPhoneNumber = Left$(sNumToBeFormatted, 3) & "-" & _
          Right$(sNumToBeFormatted, 4)
       Exit Function
    End If

  Case 10 'Format : ##########

 FormatPhoneNumber = "(" & Left$(sNumToBeFormatted, 3) & ") " _
   & Mid$(sNumToBeFormatted, 4, 3) & "-" & _
     Right$(sNumToBeFormatted, 4)
 
   Exit Function

  Case 11 'Format ######-####

 FormatPhoneNumber = "(" & Left$(sNumToBeFormatted, 3) & ") " & _
       Right$(sNumToBeFormatted, 8)
    Exit Function

  Case 12 'Format : ### ###-####

 FormatPhoneNumber = "(" & Left$(sNumToBeFormatted, 3) & ") " & _
      Mid$(sNumToBeFormatted, 5, 3) & "-" & _
      Right$(sNumToBeFormatted, 4)
    Exit Function

  Case 13 'Format : (###)###-####
     FormatPhoneNumber = Left(sNumToBeFormatted, 5) & " " & _
        Right(sNumToBeFormatted, 8)
     Exit Function


  Case Else
        'Return Value Passed
     FormatPhoneNumber = sNumToBeFormatted
          
End Select

End Function

Friday, January 26, 2007 12:52:21 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]    | 
Comments are closed.
Copyright © 2014 Matt Lyons. All rights reserved.