Private Sub MyEditBox_KeyUp(KeyCode As Integer, Shift As Integer)
If KeyCode < 48 Or KeyCode > 57 Then
MyEditBox.text = Mid(MyEditBox.text, 1, Len(MyEditBox.text) - 1)
MyEditBox.SelLength = 1
MyEditBox.SelStart = Len(MyEditBox.text)
End If
End Sub
Another approach, which simply doesn't allow the use of alpha characters. If
you don't want the users notified of their transgressions, simply omit the
messageboxes:
Private Sub NumberTextbox_KeyPress(KeyAscii As Integer)
If (KeyAscii > 47 And KeyAscii < 58) Or (KeyAscii = 8) or (KeyAscii=9) Then
KeyAscii = KeyAscii
Else:
MsgBox ("You Must Enter Digits 0-9 Only!")
KeyAscii = 0
End If
End Sub
Or to also allow the use of Decimal Points
Private Sub NumberTextbox_KeyPress(KeyAscii As Integer)
If (KeyAscii > 47 And KeyAscii < 58) Or (KeyAscii = 8) Or (KeyAscii = 46) or
(KeyAscii=9) Then
KeyAscii = KeyAscii
Else:
MsgBox ("You Must Enter Digits 0-9 or a Decimal Point Numbers Only!")
KeyAscii = 0
End If
End Sub
Private Sub NumberTextbox_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case 48 To 57, 8 To 9, 46
KeyAscii = KeyAscii
Case Else
KeyAscii = 0
End Select
End Sub
it's perhaps a little easier for a person to read the ranges in a
multi-range situation like this, but has no other advantage over an If
statement, AFAIK.
Private Sub NumberTextbox_KeyPress(KeyAscii As Integer)
If Chr(KeyAscii) Like "[!0-9.]" And KeyAscii <> vbKeyBack Then
KeyAscii = 0
End Sub
Omit the . character if you don't need decimal points, add a -
character AFTER the . if you need negative numbers. The code between
the Private and End Sub lines should all be on one line.