Enabling a control based on multiple criteria

  • Thread starter Thread starter Kurt Heisler
  • Start date Start date
K

Kurt Heisler

This code will enable txtReason if cboFavColor = "Green," and disable
txtReason if cboFavColor <> "Green":

Me.txtColors.Enabled = IIf(Me.cboFavColor = "Green", -1, 0)

If I want to expand the criteria to include "Green" OR "Blue", can I
do something like:

Me.txtColors.Enabled = IIf(Me.cboFavColor = "Green" OR "Blue", -1,
0)

This doesn't work but I suspect it's because I have the syntax wrong.
Suggestions?
 
Me.txtColors.Enabled = IIf(Me.cboFavColor = "Green" OR Me.cboFavColor =
"Blue", -1, 0)

or

Me.txtColors.Enabled = IIf(Me.cboFavColor IN ("Green", "Blue"), -1, 0)
 
This code will enable txtReason if cboFavColor = "Green," and disable
txtReason if cboFavColor <> "Green":

Me.txtColors.Enabled = IIf(Me.cboFavColor = "Green", -1, 0)

If I want to expand the criteria to include "Green" OR "Blue", can I
do something like:

Me.txtColors.Enabled = IIf(Me.cboFavColor = "Green" OR "Blue", -1,
0)

This doesn't work but I suspect it's because I have the syntax wrong.
Suggestions?
OR looks like the English language conjunction, but it isn't. It's an operator
in Boolean Algebra, just as + or - is an operator in arithmatic. It will take
two expressions and return TRUE if either or both of them are TRUE (meaning
not equal to 0, in the VBA universe), and FALSE if they are both false.

The expression

Me.cboFavColor = "Green"

might or might not be true, but

"Blue"

certainly is (it's nonzero); so the control should always enable.

Since the Enabled property is either TRUE or FALSE, you can just use

Me.txtColors.Enabled = (Me.cboFavColor IN ("Green", "Blue"))
 
Both options ...

John's: Me.txtColors.Enabled = (Me.cboFavColor IN ("Green", "Blue"))

and

Douglass': Me.txtColors.Enabled = IIf(Me.cboFavColor IN ("Green",
"Blue"), -1, 0)

.... give this error:

"Compile error: Expected: ) " and highlight the IN.
 
Both options ...

John's: Me.txtColors.Enabled = (Me.cboFavColor IN ("Green", "Blue"))

and

Douglass': Me.txtColors.Enabled = IIf(Me.cboFavColor IN ("Green",
"Blue"), -1, 0)

... give this error:

"Compile error: Expected: ) " and highlight the IN.

Hrm. Rats... can't use SQL syntax in this context!

You'll need to use OR:

Me.txtColors.Enabled = (Me.cboFavColor="Green" OR Me.cboFavColor="Blue")
 
Bummer. Was hoping for less code.

Hrm. Rats... can't use SQL syntax in this context!

You'll need to use OR:

Me.txtColors.Enabled = (Me.cboFavColor="Green" OR Me.cboFavColor="Blue")
 
I also discovered that if you don't use the IIf ... .-1, 0 arguments,
you will get an "Invalid Use of Null" error if the user deletes his
selection (and leaves the field blank), or if you put the line in the
forms OnCurrent event (which is usually desirable in order to enforce
the conditions when moving from record to record).
 
Back
Top