Mathias
Mathias

Reputation: 41

vbscript - if statement with returned value from a function?

I have a function to show a MsgBox with a text selected from an array.

'# show the choosen message
Public Function ShowMessage(which)  
    ShowMessage = MsgBox(Message(which),vbyesno,"title")
end Function

The returnvalue from this function is the return value from the MsgBox itself. When I then try to ask for that value with an if-statement i get an error message saying that this is a wrong value assingment for that function.

if ShowMessage = vbYes then
    MsgBox "clicked ok"
    StartProgram("notepad.exe")
else
    MsgBox ("some error occurred")
end if

When i assing the value of ShowMessage to var1 and go for it with the if-statement I get no error messages.

'# show the choosen message
Public Function ShowMessage(which)  
    ShowMessage = MsgBox(Message(which),vbyesno,"title")
    var1 = ShowMessage
end Function

....

if var1 = vbYes then
    MsgBox "clicked ok"
    StartProgram("notepad.exe")
else
    MsgBox ("some error occurred")
end if

Why can't I get access the value direct in that statement, or am I doing something wrong here?

Upvotes: 0

Views: 7867

Answers (2)

Andrew Cooper
Andrew Cooper

Reputation: 32596

You can't just use the name of the function like it's a variable, because it isn't.

You have to invoke the function to get it's return value. The value can either be used directly, or stored in a variable for use later.

You can't do this:

ShowMessage("Polly want a cracker?")  ' The function is called here, the return value is lost
if ShowMessage = vbYes then           ' This does not get the return value
   ...
end if

You have to do either this:

if ShowMessage("Polly want a cracker?") = vbYes then    ' Return value used directly
    ...
end if

or this:

answer = ShowMessage("Polly want a cracker?")      ' Return value stored ...
if answer = vbYes then                             ' ... and then used here
    ....
end if

Upvotes: 1

That function needs a parameter, try this:

Public Function ShowMessage(which)  
    ShowMessage = MsgBox(which,vbyesno,"title")
end Function

if ShowMessage("Heya, I'm a message") = vbYes then
    MsgBox "clicked ok"
    StartProgram("notepad.exe")
else
    MsgBox ("some error occurred")
end if

Upvotes: 1

Related Questions