If/Then in form On Close or Command On Click

N

nybaseball22

Hello. Is there a way to code a command button with an if/then
statement that will run a macro if the statement is true or run a
different macro if a statement is not true?

Example:

=IIF([Expense] is Null, Error, Close)

Thanks
 
F

fredg

Hello. Is there a way to code a command button with an if/then
statement that will run a macro if the statement is true or run a
different macro if a statement is not true?

Example:

=IIF([Expense] is Null, Error, Close)

Thanks

Private Sub MyButton_Click()
If IsNull([Expense]) Then
DoCmd.RunMacro "MacroName"
Else
DoCmd.RunMacro "OtherMacroName"
End IF
 
J

John W. Vinson

Hello. Is there a way to code a command button with an if/then
statement that will run a macro if the statement is true or run a
different macro if a statement is not true?

Example:

=IIF([Expense] is Null, Error, Close)

Thanks

Very easy to do in VBA; I don't do macros so I'm not sure, though I suspect it
could. The VBA can be entered by clicking the ... icon by the click event of
the button, choosing Code Builder, and entering

Private Sub buttonname_Click() <<< Access gives you this line for free
If IsNull(Me!Expense) Then
MsgBox "Error! Expense must be filled in.", vbOKOnly
Else
DoCmd.Close acForm, Me.Name
End If
End Sub


You may also (or instead) want to put code in the Form's BeforeUpdate event to
prevent saving a record with the field null, if that's the intention.

John W. Vinson [MVP]
 
N

nybaseball22

Thank you John. This works great. Now can I take it a step further
and say - if 'Expense' OR 'ExpDate' OR 'AnotherField' are null,
DoCmd.etc, otherwise DoCmd.etc2???

Thanks John.
 
J

John W. Vinson

Thank you John. This works great. Now can I take it a step further
and say - if 'Expense' OR 'ExpDate' OR 'AnotherField' are null,
DoCmd.etc, otherwise DoCmd.etc2???

Almost like that, at its simplest:

If IsNull([Expense]) Or IsNull([ExpDate] OR IsNull([AnotherField]) Then
<do something>
Else
<do something else>
End If

Or you can have seperate sequential If/Then/Else/End If blocks, as
appropriate.

John W. Vinson [MVP]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top