Log in

View Full Version : Require user input for a text box



will1128
09-20-2010, 01:43 PM
I'm trying to set this up such that if a user presses Tab or Enter and the text box is required and contains no data a MsgBox is displayed the focus of the cursor is set back to the text box.

My MsgBox is only displayed when I type into the text box, delete the typed text and then tab. If I press tab when nothing has been entered, nothing happens.

How do I make sure a user who is using my form has filled in all my required textboxes?

The code I have which does display the message box when I type and then delete text is.


Private Sub TextBox7_Change()
If Me.TextBox7.Text = "" Then
MsgBox "This is blank. Please Enter in."
End If
End Sub

gmaxey
09-20-2010, 01:48 PM
Will,

You need to use the "Exit" event. There are some examples here:
http://gregmaxey.mvps.org/Validate_UserForm_TextEntry.htm

will1128
09-20-2010, 01:55 PM
What if I'm not using a user Form and a Word document with a bunch of textboxes?

fumei
09-21-2010, 10:10 AM
Then switch to using a userform, and then fill in the contents into the document. Is there a particular reason not to use a userform? It is far better that way, with the ability to do error trapping.
Private Sub TextBox7_Change()
If Me.TextBox7.Text = "" Then
MsgBox "This is blank. Please Enter in."
End If
End Sub
"The code I have which does display the message box when I type and then delete text." Yes, that is because it is the Change event. There is no Exit event for ActiveX controls IN the document.

If you used formfields instead, you could use an OnExit macro to test if the value is "".

However, that still requires the user to enter it in the first place. If a user never goes into the formfield/ActiveX control there is no testing. You would have to erro trap either the Save event, or the Close event.

BTW: your attachment has no code, nor does it seem you are using Option Explicit.