Access VBA, If - End if, what ends?

mort

Registered User.
Local time
Today, 15:07
Joined
Mar 19, 2018
Messages
30
Hi,

Probably an easy question, but I havent found any good answers to it.

Say you have a code with several If statements. Something like this:
If me.checkbox = true then
If msgbox ("Do you want to continue", VbYesNo) = VbYes then
docmd.openform "formB"
else
Cancel=true
End if
End if

In this short example there are 2 If-statements and 2 End if`s. My question is this:

Which of the two If`s does the red End if end? Is it the first or is it the last?
 
They work from the inside ... out just like all similar code
So the final green statement closes the first If and the red closes the second.

Indenting helps show what's happening

Code:
If me.checkbox = true then
    If msgbox ("Do you want to continue", VbYesNo) = VbYes then
        docmd.openform "formB"
    Else
        Cancel=true
    End if
End if
 
Last edited:
the answer becomes apparent when you indent your code

Code:
    If Me.CheckBox = True Then
        If MsgBox("Do you want to continue", vbYesNo) = vbYes Then
            DoCmd.OpenForm "formB"
        Else
            Cancel = True
        End If
    End If
 
The second if since it is inner End If. Feim which sub are this code? If form user defined sub, the fault is in Cancel. You only Cancel on intrinsic access subs, ie BeforeUpdate event, open and unload event of form.
 
In this short example there are 2 If-statements and 2 End if`s. My question is this:

Which of the two If`s does the red End if end? Is it the first or is it the last?
Turns out to be not too easy to describe this in words. :-/ It becomes pretty obvious when the code is properly formatted, though.

Code:
If me.checkbox = true then
    If msgbox ("Do you want to continue", VbYesNo) = VbYes then
        docmd.openform "formB"
    else
        Cancel=true
    End if
 End if
Does this answer the question?
 
Thanks for all your answers. I understand it perfectly now :)
 
@ Mort,

A habit I used to have was commenting which "End" ends which structure.

Code:
If me.checkbox = true then
   If msgbox ("Do you want to continue", VbYesNo) = VbYes then
      docmd.openform "formB"
   else
      Cancel=true
   End if 'If msgbox ("Do you want to continue", VbYesNo) = VbYes then
End if 'If me.checkbox = true then

Can make large structures much easier to follow. Fortunately I haven't had to do things like that for a while, but it some times made following complex code MUCH easier.
 
Aren't you getting a compile error. -- If without end ---
 

Users who are viewing this thread

Back
Top Bottom