I have a long code on worksheet event which contains a lot of IF conditions and nested IF.
Sometimes, I forget to add the end if ,so when I debug the code ,got this Compile error:Block If without End If
.
The error meaning is very clear , and I depend on my eye to find this missing IF.
Because the code on worksheet event , I cannot use F8 (Step Into).
So, Is there any programmatic method to Find / Debug (Find Location) of the missing End If
.
In advance, grateful for any helpful comments and answer.
CodePudding user response:
Go through your code make sure you have no single line If (condition) Then (do something)
statements. Means after every Then
is a line break and no statement following in that line. The statements follow in the next line below and are closed with an End If
.
If a Then b = 1 ' single line statement
avoid them and use always blocks like
If a Then
b = 1
End If
This looks a bit cumbersome but makes it much easier to find issues.
Then go through your code make sure you indent everything correctly. This way you will find out if there are any blocks that are not closed.
Note that the error message might be missleading and does not come from a missing End If
. Even your compiler tells you that, it just means that the compiler was waiting for an End If
where something else came, so it just couldn't find it in the expected position:
For example if you just mix up the position of End If
and End With
and you have a bad code formatting like below, you will get the missing End If
compiler message:
If Condition = True Then
With ActiveSheet
End If
End With
But if you indent your code correctly and format it nicely you will easily see that something is wrong:
If Condition = True Then
With ActiveSheet
End If ' should be `End With` inner block needs to close first
End With
Now you cleary see that End If
and End With
got mixed up and don't match their If
and With
. In nested blocks, the inner blocks need always to be closed first.