• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Formatting Textbox to type phone numbers only

Hi,

I have a Textbox called PhoneNumber and I want to be able only to enter the phone number in this format ###-###-#### and if for some reason I enter a letter or another symbol I want to receive a notification saying "Please enter numbers only"

I was trying to put together 2 codes and so far, it allows me to enter only phone numbers and I receive a notification.

This is what is not working for me:

when I type the first 3 numbers, it is fine, as soon as the symbol (-) gets populated by itself its telling me to enter numbers only.

1 - How do I fix this code in order to let me enter numbers only and I don't receive a notification when the symbol (-) gets populated automatically

I attached a sample document .

Thank you
 

Attachments

  • Primary - Blue Print .xlsm
    115.4 KB · Views: 5
Hi:

Find the attached.
Code:
Private Sub PhoneTextBox_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Dim str As Variant

str = PhoneTextBox.Value

If Mid(str, 4, 1) <> "-" Or Mid(str, 8, 1) <> "-" Then
    MsgBox "Please enter numbers ###-###-#### format"
    Exit Sub
End If
For i% = 1 To Len(str)
    Select Case Asc(Mid(str, i, 1))
        Case 65 To 90, 97 To 122
            MsgBox "No alphabets allowed"
            Exit Sub
            Exit For
    End Select
    Next

End Sub

Thanks
 

Attachments

  • Primary - Blue Print .xlsm
    108.4 KB · Views: 3
Thank you Nebu,

How can the symbol "-" be populated automatically. would you mind checking the document I attached previously? also in that attachment when I type a letter I receive a notification right away saying to enter only numbers
 
Hi

the below code works really good. It will only allow you to write numbers and It will populate the symbol "-" automatically.

Code:
Private Sub PhoneTextBox_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
        Select Case Len(PhoneTextBox) + 1
            Case 4, 8: KeyAscii = 45 ' set press at "-"
            Case 1, 2, 3, 5, 6, 7, 9, 10, 11, 12: KeyAscii = KeyAscii * -CLng(Chr(KeyAscii) Like "[0-9]")
            Case Is >= 13: KeyAscii = 0 '' Stop input in textbox
        End Select
End Sub

Enjoy
 
Back
Top