Easy way to write Nested IF THEN ELSE IF Statements... (1 Viewer)

MackMan

Registered User.
Local time
Today, 13:07
Joined
Nov 25, 2014
Messages
174
Here's a question for the experts.

How do you write complex nested IF THEN ELSE END IF statements, so you don't get mixed up or confused with what happens first, next, last and so on.

I'm trying to write just this, and I'd like to try to figure this out for myself.

How do you start?
How do you know what IF statement to put first?
Then how would you know where to put ELSE, or END IF?

Before you start with the VBA, what are the foundations for making it work successfully, know where you are, know where to put END IF etc?

I've seen many times when using VBA people set up an initial foundation for writing code. For example when needing to put something in quotes, they do "" then enter the text in between, so they don't get errors on running (A very simple, crude example I know, but is there a similar basis for nested IFs)

I was just wondering how it's done right, first time?
 

plog

Banishment Pending
Local time
Today, 07:07
Joined
May 11, 2011
Messages
11,646
I don't know if you are looking for a logic or a formating answer, so I will give both.

Formatting--are you saying its hard for your eyes to see where one if starts and its next else starts? If so, you use tabs and spaces:

Code:
If (Criteria1=True) Then
    Criteria1 True Statements Here
Else If (Criteria2=True) Then
    Criteria2 True Statements Here
Else...

If you logically find it hard to follow, if/else aren't usually the best way to implement logic. If you are testing the same variable over and over, you should use a Case statement (https://msdn.microsoft.com/en-us/library/cy37t14y.aspx). Even if you aren't testing the same variable, I find its easy to implement logic that doesn't require the else--just the If. Sometimes that involves a variable to see if you have acted before:

Code:
ActionTaken=False

If (Criteria1=True) AND (ActionTaken=False) Then
    Criteria1 Action here
    ActionTaken=True
    End If 
If (Criteria2=True) AND (ActionTaken=False) Then
    Criteria2 Action here
    ActionTaken=True
    End If
If (Criteria3...

The simple answer is that If/Else's should be avoided to make things clearer.
 
Last edited:

MarkK

bit cruncher
Local time
Today, 05:07
Joined
Mar 17, 2004
Messages
8,181
Presumably you write the complex if statement to mimic some business rule or observable reality, so how you write it is determined by that pre-existing logic.

A few things that might make it easier:
1) pre-solve the logic for some small set of test data that you can use to test your result.
2) Abandon the idea that you need to get it right the first time. Development is an iterative process whereby you try something, study how it fails, correct that failure, and then study the next failure. To me, solutions commonly come as a surprise, because I'm just running the next test.
3) Use subroutines. Consider how obvious it is what happens in this code . . .
Code:
Private Sub cmdImportantOperation_Click()
   If ValidateSideways(me.testID) And ValidateLengthwise(me.testID) Then
       DoSomethingImportant me.testID
   Else
       MsgBox me.testID & " could not be validated"
   End If
End If
That code makes use of three calls to subroutines, two of them for boolean validation, exactly what you are asking about if you want to make complex decisions in code using IF blocks. So don't write a complex IF...ElseIF...Else...End If block. Write a single validation routine, that calls other subroutines as required, which call other subroutines as required, and do it such a way that each routine is dead simple, performs one action or operation, and whose function can be determined in less than 10 seconds.

Actually, a general rule when you write code--not just if bocks: Write dead simple subroutines that perform one action or operation, and whose purpose is obvious at a glance. For boolean decision making, write functions that return booleans, use those as expressions in your IF blocks.

Hope this helps,
 

Cronk

Registered User.
Local time
Today, 22:07
Joined
Jul 4, 2013
Messages
2,772
MackMan

In addition to the good advice in the previous responses, in dealing with nested IF statements, it depends on what you are trying to do (logic)

An example where you want to prompt the user to choose between printed output and emailed output, the choice cannot be offered if the recipient has no email address.
Code:
if msgbox("Do you want to print a receipt?", 36, "Generate receipt?") = vbyes then
  if Recipient has email then
    if msgbox("do you want to email?",36,"Print or email?") = vbyes then
       Generate email code
    else
        Print code
    endif
  else
     Print code
  endif
endif
 

Solo712

Registered User.
Local time
Today, 08:07
Joined
Oct 19, 2012
Messages
828
One of the most important things when writing complex if-then-else logic is to understand the scope of the statement. Things become much easier if you keep indenting progressively to separate the execution paths for all the possible scenarios.

Code:
            If condition#1 Then
                 'statements for all condition#1=true situations 
              If condition#2 Then 
                 ' statements if condition#1 and condition#2 are true
              Else  ' condition#2 = false                                     
                 ' statements for all condition#1=true/condition#2=false situation 
                 If condition#3A Then 
                 '  statements for condition#1=true/condition #2=false/condition#3A=true  
                 ElseIf condition#3B Then 
                 ' statements for condition#1=true/condition #2=false/condition#3B=true
                 End If  'close scope fot conditions#3A/#3B
                 '--------------------------------------------------
              End If  'close scope for condition#2                 
              '-----------------------------------------   
           Else  'condition#1=false
              ' statements for all condition#1=false situations
              If condition#4 =true
              ' statements for condition#1=false/condition#4=true
              End if  'close scope for condition#4
              '------------------------------------------ 
           End If
           'close scope for condition#1
           '---------------------------------

One of the tricks of writing succesfully a really complex if-then-else gates is being able to ientify situation when you need to open a "new scope" (or an indented level). Try to reduce the number of levels by using the "ElseIf" structure instead of "Else" and a new scope "If" wherever you can. You can do that in all situations where the first statement after the "Else" is another "If". You only need to open new (indented) scope where there is common processing for the TRUE or FALSE side that the "Else" represents.

Best,
Jiri
 

MackMan

Registered User.
Local time
Today, 13:07
Joined
Nov 25, 2014
Messages
174
Hello all. Many thanks for you input on this. As a result of your help, I managed to figure out what I needed. I'm very impressed by your knowledge, and appreciate your replies, despite knowing how busy you are.

Again, Super thanks.
 

ronaldff

Registered User.
Local time
Today, 13:07
Joined
Aug 31, 2009
Messages
24
Hello MackMan

Try drawing your logical flow in the form of a logic diagram - a flow diagram. In the early days of programming - machine code etc.., this was the only way to perceive the flow of control. For example, "if" is represented by a diamond containing a question- enter through the top and exit through one point for "yes" and the other for "no". The third exit was often used for a third possibility in that language. A statement is represented by a rectangle, number circles indicate exit to another part of the diagram, or input from somewhere else.

Once your diagram is complete, you can check and fine tune your flow - and then write your code!

Maybe this approach is too old fashioned for younger programmers - but worth a try for complex if..then..else

I should add that the first computer I ever had to program had 8 switches - 7 for data and one for parity

Ron
 

Users who are viewing this thread

Top Bottom