Jump to content

Prohibiting executable statements outside procedures

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
ozmo

ozmo

    Newbie

  • Members
  • Pip
  • 2 posts
As I've discovered while learning VBA, most executable statements cannot be placed outside subs and procedures (e.g., in the header/declarations section). I found this when I attempted to initialize a string variable immediately after its declaration, only to be rebuked by an "Invalid outside procedure" error.

I understand the rule, but I'm just wondering what the justification for this convention would be? Does it improve the quality of code somehow?

Thanks for your input.

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
At a guess, nothing outside a sub/procedure CAN be executed. Most event driven languages provide a special sub/procedure that can be run at startup.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
ozmo

ozmo

    Newbie

  • Members
  • Pip
  • 2 posts
To clarify, I guess what I meant was, why *cant* you execute commands outside of procedures, and why a decision was made by the language's authors for this to be the case.

You answered the question perfectly, though. Like you said, because the language is event-driven, executable statements are contained in procedures which are triggered as appropriate. It would be awkward and probably unnecessary to force the execution of statements in lieu of an event occurrence, so this is not allowed.

I felt the urge to put some initializing code in the declarations section so that I could see all of it clearly on top upon opening the module; as an alternative, I'll just ensure that the OnLoad event procedure is listed at the top of my modules to achieve the same result.

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
I'll use C++ as an example, since I'm more familiar with it:
Code ALWAYS starts by calling the main() function. When you exit the main function, the program ends with it. In VB, you will have something similar. A function is declared (which you may not ever see) that initializes various event listeners. It then sits waiting for those event to be triggered. There is nothing outside those functions that ever gets executed, so a statement outside them just sits there being useless.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog