VB - Numeric Textbox input only
As you type the text
VB Code:
Private Sub Textbox1_KeyPress(index As Integer, KeyAscii As Integer)
'Accepts only numeric input
Select Case KeyAscii
Case vbKey0 To vbKey9
Case vbKeyBack, vbKeyClear, vbKeyDelete
Case vbKeyLeft, vbKeyRight, vbKeyUp, vbKeyDown, vbKeyTab
Case Else
KeyAscii = 0
Beep
End Select
End Sub
Clicking a command button to validate
VB Code:
Private Sub Command1_Click()
If Not IsNumeric(Text1.Text) Then
MsgBox "Please enter numbers only.", vbInformation
'you may also consider erasing it
Text1.Text = ""
End If
End Sub
Re: VB - Numeric Textbox input only
You know, every textbox has a "Validate" event...
VB Code:
Private Sub Text1_Validate(Cancel As Boolean)
If Not IsNumeric(Text1.Text) Then
MsgBox "Please enter numbers only.", vbInformation
'you may also consider erasing it
Text1.Text = ""
Cancel = True
End If
End Sub
Much better than checking in multiple places...
Re: VB - Numeric Textbox input only
My code checks as each character is typed, therefore literally stopping you typing text
Re: VB - Numeric Textbox input only
Hi x-ice,
I'm pretty new working with VB. Actually I'm usign your code to have a numeric textbox. Thank you and thank VB Forums. I have another problem: What do I need to to allow negative numbers and limit to specific number of decimals?
Yor help will be highly appreciated.
Necalabria
Re: VB - Numeric Textbox input only
Private Sub txtCTC_KeyPress(KeyAscii As Integer)
If Chr(KeyAscii) Like "[a-z]" And KeyAscii <> 8 Then KeyAscii = 0
End Sub
This works good. :)
Re: VB - Numeric Textbox input only
I think it is also good to mention for newer programmers that you can add as many validations as you want with "If Else" statements to clean up code using your second set of code
ex. from personal project for a POS system for a coffee shop
If Not IsNumeric(CappacinoTextBox.Text) Then
MsgBox("Please enter numbers only.", vbInformation)
'Validate CappacinoTextBox
CappacinoTextBox.Text = ""
ElseIf Not IsNumeric(LatteTextBox.Text) Then
MsgBox("Please enter numbers only.", vbInformation)
'Validate LatteTextBox
LatteTextBox.Text = ""
ElseIf Not IsNumeric(ChaiTeaTextBox.Text) Then
MsgBox("Please enter numbers only", vbInformation)
'Validate ChaiTeaTextBox
ChaiTeaTextBox.Text = ""
End If
Will validate every one of those text boxes in one block of code so anyone who picks up your code later can get all your validations in one place.
Re: VB - Numeric Textbox input only
Text1_Validate(Cancel As Boolean) doesn't work
Re: VB - Numeric Textbox input only
laudeniold has a good idea to start with but it doesn't stop typing in special characters
Re: VB - Numeric Textbox input only
Quote:
Originally Posted by
x-ice
My code checks as each character is typed, therefore literally stopping you typing text
But it doesn't consider pasting characters, for instance, when using the edit box's context menu.
Therefore, you will need additional code in the Change or Validate events.