ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   textbox (https://www.excelbanter.com/excel-programming/305459-textbox.html)

tamsin

textbox
 
Is there an easy way of only allowing numbers and one
decimal point to be entered in a textbox?

I've found a rather long winded way of solving the number
bit (see code below) but checking each previously entered
character to see if its a decimal point has proved to be a
problem; and there must be a simpler way!

Private Sub TextBox1_Change()
If TextBox1.Text < "" Then
If Asc(Right(TextBox1.Text, 1)) < 48 _
Or Asc(Right(TextBox1.Text, 1)) 57 Then
TextBox1.Text = _
Left(TextBox1.Text, TextBox1.TextLength - 1)
End If
End If
End Sub

Bernie Deitrick

textbox
 
tamsin,

Use this event if you require a decimal point to be entered:

Private Sub TextBox1_AfterUpdate()
If InStr(1, TextBox1.Text, ".") 0 Then Exit Sub
MsgBox "You need to enter a decimal point."
UserForm1.TextBox1.SetFocus
End Sub

Use this event to allow only numbers to be entered:
Private Sub TextBox1_Change()
Dim myVal As Long
If TextBox1.Text < "" Then
On Error GoTo Changeback
myVal = CLng(TextBox1.Text)
End If
Exit Sub
Changeback:
TextBox1.Text = _
Left(TextBox1.Text, TextBox1.TextLength - 1)
End Sub

HTH,
Bernie
MS Excel MVP

"tamsin" wrote in message
...
Is there an easy way of only allowing numbers and one
decimal point to be entered in a textbox?

I've found a rather long winded way of solving the number
bit (see code below) but checking each previously entered
character to see if its a decimal point has proved to be a
problem; and there must be a simpler way!

Private Sub TextBox1_Change()
If TextBox1.Text < "" Then
If Asc(Right(TextBox1.Text, 1)) < 48 _
Or Asc(Right(TextBox1.Text, 1)) 57 Then
TextBox1.Text = _
Left(TextBox1.Text, TextBox1.TextLength - 1)
End If
End If
End Sub





All times are GMT +1. The time now is 10:06 AM.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
ExcelBanter.com