Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Give textbox focus

Status
Not open for further replies.

Mollethewizard

IS-IT--Management
Nov 18, 2002
93
SE
I have a minor problem. How can I prevent a user from exiting a textbox in a user form if the entry is not correct, in this case anything but numbers?

In the textbox key-press event I’ve written some code that give the user a message – but how on earth can I give the textbox focus again?

The code goes like this:

Private Sub txtKronor_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii >= 48 And KeyAscii <= 57 Then
Else
KeyAscii = 0
Meddelande = MsgBox(&quot;Ogiltig inmating - se Makroanvisningar&quot;, 48, &quot;Ogiltig inmatning&quot;)
With frmDodsbo.txtKronor
.Value = &quot;&quot;
End With
End If
End Sub

Any help would be much appreciated

Mollethewizard
 
I can see that you only want integers in the text box. I use this Sub to only allow integers. It doesn't require the need to .setfocus because the focus is not lost; the user stays in the text box.
Private Sub txtINFO8_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If Chr(KeyAscii) < 0 Or Chr(KeyAscii) > 9 Then
KeyAscii.Value = 0
Beep
End If
End Sub


********************
What's the best way to get the answers you need?? See FAQ222-2244 for details!
 
Hi Mollethewizard,

Put your code in the BeforeUpdate event. This won't catch every keystroke but you can examine the complete entry and if it is invalid, display a message if you want and then set Cancel=True. This stops further processing of the form and redisplays it with the focus on the textbox.

Code:
Private Sub txtKronor_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)

If Not IsNumeric(Me.txtKronor) Then

    Meddelande = MsgBox(&quot;Ogiltig inmating - se Makroanvisningar&quot;, 48, &quot;Ogiltig inmatning&quot;)
    Me.txtKronor.Value = &quot;&quot;
    Cancel = True

End If

End Sub

Enjoy,
Tony
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top