MsgBox () - why does it work with one parameter but not multiple parameters?

This is a very theoretical question that I would like to know about expanding my understanding of the VBA language, but did not find anything in the official documentation and on previous questions here and on other forums (maybe it's just not worth wondering why?).

If I write:

MsgBox "myPrompt", vbYesNo, "MyTitle"

      

a message box appears with a custom prompt, button and name. However, if I write this, I get a compilation error (Expected "="):

MsgBox ("myPrompt", vbYesNo, "MyTitle")

      

So far it's all about the syntax. In the second case, I have to store the return value of the function into a variable, so I pretty much agree that the "=" sign is expected. However, the following line will work:

MsgBox("myPrompt")

      

and returns a value anyway 1

, which I can see by simply doing

a = MsgBox("myPrompt")
MsgBox a

      

So, the reason it MsgBox ("myPrompt", vbYesNo, "MyTitle")

doesn't work without an assignment no longer seems, in my opinion, to be related to the expected assignment to a variable, as the compilation error says. Can anyone explain this to me please?

+3


source to share


1 answer


At a very high level, it has to do with how the compiler interprets the commands.

As you noted, both of these work:

MsgBox "Hello World"
MsgBox ("Hello World")

      

But it won't (without variable assignment):

MsgBox ("Hello World", vbYesNo, "Title")

      

This is because (no assignment), VB thinks there is one parameter value "Hello World", vbYesNo, "Title"

. This is obviously not true and you get a welcome error message.

If you try this, it will work.



MsgBox ("Hello World"), (vbYesNo), ("Title")

      

As each parameter is provided in its own set of brackets.

Syntactically, this is exactly the same as the operator MsgBox ("Hello World")

above. You just put each parameter in parentheses instead of one.


EDIT

MsgBox ("Hello World")

works because it ignores parentheses just like it does with a simple integer assignment, for example x = (2)

.

+3


source







All Articles