VBA IF THEN with an OR

P

Papa Jonah

I would like to have an IF Then statement that is of the ilk, If this or that
then...
How do I put the "or" part of it in there? I know how to do the or(x,y)
thing in a worksheet.
Thanks,
Papa J
 
M

Mike H

Hi

If x = 1 Or y = 2 Then
'do something
Else
'do something else
End If


--
Mike

When competing hypotheses are otherwise equal, adopt the hypothesis that
introduces the fewest assumptions while still sufficiently answering the
question.
 
S

Sheeloo

IF (cond1 OR Cond2) Then
....
Else
....
End If

eg.

Sub test()
If ((Range("a20") = 10)) Or (Range("B20") = 5) Then
MsgBox "Either A20 is 10 or B20 is 5"
Else
MsgBox "both are false"
End If
End Sub
 
R

Rick Rothstein

In the worksheet world, OR is a function (hence, the arguments enclosed
within its parentheses); however, in the VB world, Or (along with And, Xor
and a couple of others) are operators just like =, <>, >=, etc. are and, as
such, it goes between the "operands" it is being used with. So, it would be
used like this...

If Condition1 Or Condition2 Then
 
J

Joe User

Papa Jonah said:
I would like to have an IF Then statement that is of the ilk, If this or
that
then...
How do I put the "or" part of it in there? I know how to do the or(x,y)
thing in a worksheet.

Just as you wrote it:

If this Or that Then doThis

where "this" and "that" are expression like x<1 and 10<x.

But beware: all expressions are evaluated. So, for example, you might want
to write the following:

If x>0 And y/x > 10 Then doThis

thinking that the x>0 condition protects against a div-by-zero error in
y/x>10. It does not! You have to write something like:

If x>0 Then
If y/x > 10 Then doThis
End If

Similar situations arise with Or, of course.
 
P

Papa Jonah

Thanks again Mike

Mike H said:
Hi

If x = 1 Or y = 2 Then
'do something
Else
'do something else
End If


--
Mike

When competing hypotheses are otherwise equal, adopt the hypothesis that
introduces the fewest assumptions while still sufficiently answering the
question.
 
Top