Textbox value

  • Thread starter Thread starter Shamsul
  • Start date Start date
S

Shamsul

Hi

How can you restrict users from only entering numbers in a
textbox; and if text was entered a error message will be
displayed.

Thanks

Sham
 
Sham,

Assuming a userform, this will do as you ask

Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
With Me.TextBox1
If Not IsNumeric(.Text) Then
.SelStart = 0
.SelLength = Len(.Text)
.SetFocus
Cancel = True
MsgBox "Invalid data"
End If
End With
End Sub

An alternative is to trap the input, and only allow numerics

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii < 48 Or KeyAscii > 57 Then
Application.EnableEvents = False
KeyAscii = 0
Application.EnableEvents = True
End If
End Sub


--

HTH

Bob Phillips
... looking out across Poole Harbour to the Purbecks
(remove nothere from the email address if mailing direct)
 
Back
Top