if ... then ... else with dates

SueBK

Registered User.
Local time
Today, 13:10
Joined
Apr 2, 2009
Messages
197
I am trying to write some 'if then else' code using date fields.

What I have managed to get working is:

Code:
Private Sub StartDate_AfterUpdate()
If StartDate.Value > #1/1/1900# Then
Me.Started.Value = True
End If
End Sub

If a date is entered into the "startdate" field then the "started" check box is marked.

What I can't work out how to do is use "null" in my code. Eg: if the date is a null value, the check box is unchecked. Naturally, but default, both the date field and check box are null; but occassionally I can see someone putting in a date by error and then deleting it. I've tried all sorts of permutations, but can't crack it.

I want the check box to be unmarked if the startdate value is null.
 
I think you are looking for "ISNULL" in your if statement, but woulden't this validation be better if you put it in Before_Update instead?

Code:
Private Sub startdate_BeforeUpdate(Cancel As Integer)
If IsNull(startdate.Value) Or (startdate.Value < #1/1/1900#) Then
    Me!started.Value = False
    Else
    Me!started.Value = True
End If
End Sub

JR
 
This is the code I used (note the names of the controls);

Code:
Private Sub txtStartDate_AfterUpdate()
    If IsNull(Me.txtStartDate) Or Me.txtStartDate = "" Then
        Me.chkStarted.Value = False
    Else
    If Not (IsNull(Me.txtStartDate)) Then
         Me.chkStarted = True
    End If
    End If
End Sub

I have attached a sample for you, I have tested it and it works.

When the sample opens you will see the form, now delete the date, then click on the controls that has John in it and you will see that the Started tick is removed, now put a date back into Start Date move the focus again to John and you will see that the tick is back there.
 

Attachments

The code you've posted will set chkStarted to True, even if txtStartDate is < 1/1/1900, which ys at odds with your original post.

And unless you're going to possible be pasting data into txtStartDate,

Me.txtStartDate = ""

is really useless. Deleting previously entered data from a control does not leave a Zero-length string, it returns the control's value to Null.

And the AfterUpdate event is the usual place for this type of code. The BeforeUpdate event is appropriate if you're going to, say, make the user correct something in txtStartDate that entered incorrectly.
 
Last edited:
missinglinq,

Are you referring to my post or the one by JANR?

In my post I used txtStartDate, but it was not in the other posts.
 
I don't understand your reply my post never said anything about;

The code you've posted will set chkStarted to True, even if txtStartDate is < 1/1/1900, which ys at odds with your original post.
 
Thank you. It was the "isnull(me.xxx)" and "not isnull(me.xxx)" that was tripping me up. I was writing "me.xxxx = null".

Thanks again.
 

Users who are viewing this thread

Back
Top Bottom