We help IT Professionals succeed at work.

If else statement

trbaze
trbaze asked
on
I'm trying to write an if else statement in which the action would perform if two conditions where true.
example:
If result = 2, and time = 3, then
 
Comment
Watch Question

Guy Hengel [angelIII / a3]Billing Engineer
GOLD EXPERT
Most Valuable Expert 2014
Top Expert 2009

Commented:
in VBA:


If result = 2  and time = 3  then

Open in new window

Author

Commented:
Is that the way it is actually written?  So that both conditions must return true on the if part of the statement.  Not just one.
Guy Hengel [angelIII / a3]Billing Engineer
GOLD EXPERT
Most Valuable Expert 2014
Top Expert 2009

Commented:
yes, the  <condition 1> AND <condition 2> will return true only if both conditions return true.
Mike EghtebasDatabase and Application Developer

Commented:
more compelte verion:

If result = 2  and time = 3  then
'do action1
else
' do action2
end if
In .NET the If statement is a bit clearer:

If Result = 2 ANDALSO Time = 3 then

This does what is call 'short-circuiting' the If test.

In Access syntax

If Result = 2 and Tiime = 3 then

Both Tests are evaluated, even in the case where the First test FAILS (thsu making the value of the second test irrelevant).  In the .NET syntax, if the First test FAILS, then the second test is NOT evaluated.

Similary, in the negative test

If Result <> 2 or Time <> 3 then

The .NET syntax is

If Result <> 2 ORELSE Time <> 3 then

In the Access form, both tests will be evaluated, even when Result is in fact <> 2 (so that the result of the second test is once again irrelevant).  In the .NET syntax, only the the case where Result is actually equal to 2, will the second test be evaluated.

AW
RyanProject Engineer, Electrical
BRONZE EXPERT

Commented:
Theres some other ways.
If you just happen to care, while we're point out .net and VBA.

Excel uses an AND function.  IF(AND(result=2,time=3),"Was true","Was False")

In VBA you can implement an AND by nested IFs

If Result = 2 then
  if time = 3 then
    'both were true
  end if
end if