TextBox Validation

  • Thread starter Thread starter Gordon
  • Start date Start date
G

Gordon

Have 3 textboxes; properties: AutoTab True, MaxLength 2, IndexTab
1-2-3, TabStop True.

Event textbox1_Change()
If textbox1 > 25 Then
MsgBox "Too large of a number"
End If

Will show MessageBox, but will not take corrected number

What is the code or how to do it

Thank You
Gordon
 
Like on a userform?

I'd use a label instead of a message box.

Option Explicit
Dim BlkProc As Boolean
Private Sub UserForm_Initialize()

Me.Caption = "Get Input from User"

With Me.CommandButton1
.Caption = "Ok"
.Default = True
.Enabled = True
End With

With Me.CommandButton2
.Caption = "Cancel"
.Cancel = True
.TakeFocusOnClick = False
.Enabled = True
End With

Me.Label1.Caption = ""
End Sub
Private Sub TextBox1_Change()
If BlkProc = True Then Exit Sub
Me.Label1.Caption = ""
With Me.TextBox1
If IsNumeric(.Value) Then
If .Value > 25 Then
Me.Label1.Caption = "Please enter a smaller number"
BlkProc = True
Me.TextBox1.Value = ""
BlkProc = False
End If
Else
Me.Label1.Caption = "Please enter a number"
BlkProc = True
Me.TextBox1.Value = ""
BlkProc = False
End If
End With
End Sub

The blkproc stuff is kind of like application.enableevents. The change made by
the code will cause the _change event to fire. But by setting this flag, the
procedure starts, then stops really quickly.
 
Hi Gordon

Not knowing what and who this is for, but I think I'd do something like
this, making unwanted entries impossible:

Private Sub TextBox1_KeyDown(ByVal KeyCode As _
MSForms.ReturnInteger, ByVal Shift As Integer)
Select Case KeyCode
Case 8, 46, 48 To 57 'backspace, Delete, numbers ok:
Case 86 'Ctrl V trap:
If Shift = 2 Then KeyCode = 0
Case Else 'illegal:
Me.Caption = KeyCode
KeyCode = 0
End Select
End Sub

Private Sub TextBox1_Change()
With TextBox1
If Val(.Text) > 25 Then
'delete first digit:
.Text = Mid$(.Text, 2)
End If
End With
End Sub

If this goes for many textboxes, let a class module handle it for all of
them (which is a litle more complicated, post back if very interested).

HTH. Best wishes Harald
 
If the values you want to allow are integers 0-25 (or some limit), you may want
to use a different control.
Maybe you could use a combobox or a listbox or a scrollbar/spinbutton and a
label.
 
Back
Top