ms-accessphone-number

formatting phone numbers ms access


Sorry, another question about MsAccess.

I have data set:

Phone Number
444-514-9864
555-722-2273
333-553- 4535
000-000- 0000
550-322-6888
444-896-5371
322-533-1448
222.449.2931
222.314.5208
222.745.6001

I need it to look like (222) 896-5371. How do I do it in Ms Access or MsExcel?


Solution

  • You can use the Instr, mid, Left and Right functions to make this work. I have made 1 example, with msdn you should be able to figure out the rest

    Dim OldPhoneNumber As String
    Dim NewPhoneNumber As String
    Dim PreFix As String
    Dim PreFix2 As String
    
    ' You can replace this line in Access, just make sure the full phone number is stored in "OldPhoneNumber"
    OldPhoneNumber = Worksheets(<worksheet name>).Range(<cell name>).Value 
    
    
    PreFix = Left(OldPhoneNumber, InStr(1, OldPhoneNumber, "-", 1))
    PreFix2 = Left(OldPhoneNumber, InStr(1, OldPhoneNumber, "-", 1) - 1)
    
    NewPhoneNumber = Replace(OldPhoneNumber, PreFix, "(" & PreFix2 & ") ")
    
    Debug.Print (NewPhoneNumber)
    

    Seeing as not all your phone numbers are formatted the same way, you would have to make a different rule for every different formatted phone number (you need 1 that checks for "-" and one that checks for "." You also might want to filter out the spaces