Matteo NNZ
Matteo NNZ

Reputation: 12695

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

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

If I write:

MsgBox "myPrompt", vbYesNo, "MyTitle"

it's coming out a message box with custom prompt, button and title. However, if I write this I get a compile error (Expected "="):

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

Until now, it's all about syntax. In the second case I am supposed to store the return value of the function into a variable, so I pretty much agree on the fact the "=" sign is expected. However, the following line will work:

MsgBox("myPrompt")

and it is anyway returning the value 1, which I can see by simply running

a = MsgBox("myPrompt")
MsgBox a

So, the reason why MsgBox ("myPrompt", vbYesNo, "MyTitle") doesn't work without assignment does not seem anymore, according to me, supposed to be related to the fact that a variable assignment is expected as the compile error is saying. Could anyone kindly explain this to me, please?

Upvotes: 3

Views: 1766

Answers (1)

Jason Faulkner
Jason Faulkner

Reputation: 6578

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 this will not (without assigning to a variable):

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

This is because (without the assignment), VB thinks there is a single parameter value of "Hello World", vbYesNo, "Title". Obviously, this is incorrect and you get a friendly error message.

If you were to try this, it will work.

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

Because each parameter is provided in its own set of parenthesis.

Syntactically, this is exactly like the MsgBox ("Hello World") statement above. You are just specifying each parameter in parenthesis instead of only one.


EDIT

The MsgBox ("hello world") works because it ignores the brackets exactly as it would do with a simple integer assignment, such as x = (2).

Upvotes: 3

Related Questions