Set Focus

S

Secret Squirrel

I have a main form and a subform. I have a control on my main form called
"Date1". What I want to be able to do is if a user leaves that field blank
and starts updating controls on the subform I want a message to pop up saying
that they need to enter a date before they can enter any data on the subform.
How would I go about doing this?
 
P

pietlinden

I have a main form and a subform. I have a control on my main form called
"Date1". What I want to be able to do is if a user leaves that field blank
and starts updating controls on the subform I want a message to pop up saying
that they need to enter a date before they can enter any data on the subform.
How would I go about doing this?

Add code to the Exit event of the control, and cancel the exit if the
control is blank.

Something like

Private Sub Date1_Exit(Cancel As Integer)
If IsNull(Date1) Then Cancel = True
End Sub
 
S

Secret Squirrel

That works but the only problem is if the user wants to close the form they
can't because now they can't click on the close command button. Is there any
way to have the command buttons on the form exempt from this code?
 
J

John W. Vinson/MVP

I have a main form and a subform. I have a control on my main form called
"Date1". What I want to be able to do is if a user leaves that field blank
and starts updating controls on the subform I want a message to pop up saying
that they need to enter a date before they can enter any data on the subform.
How would I go about doing this?

Try using the Form's BeforeUpdate event to check the control.
BeforeUpdate fires when the record is about to be saved, e.g. when you
set focus to the subform. Piet's suggestion of the Exit event will
work also, but only if the user actually sets focus to the textbox -
they could skip it altogether and go right to the subform.

Try clicking the ... icon by the form's beforeupdate event, and put
code like

Private Sub Form_BeforeUpdate(Cancel as Integer)
Dim iAns As Integer
Dim strMsg As String
strMsg = "Date1 should be filled in! Click OK to do so, " _
& "or Cancel to quit without completing the record"
If IsNull(Me!Date1) Then
iAns = MsgBox(strMsg, vbOKCancel)
Cancel = True
If iAns = vbCancel Then
Me.Undo ' erase the form
Else
Me!Date1.SetFocus
End If
End If
End Sub
 
S

Secret Squirrel

Which form are you referring to? My main form or the subform? I tried to put
this code in the main form's beforeupdate event but nothing happened. It
still allowed the subform to be updated even when the Date1 field is empty.
 
S

Secret Squirrel

When I put this code in the exit event of my date field it works fine. The
only problem is I can't click on my close button to close the form if no
matter which option they choose. I want them to be able to use the close
button no matter which option they choose from the message you created in the
code.
 
Top