Calling a sub with more than one parameter results in compile error

I get "Compile error: Expected: =" when passing two variables to another sub.

Adding "void = " in front will solve the problem but it seems odd that this is best practice.

Using bracket when passing no arguments will result in the same compile error.

Sub sub1()
    sub2
    sub2 ()
    sub3 ("Hello World!")
    sub4 ("Hello World!", "Hello World! Again!")
End Sub

Sub sub2()
    MsgBox ("Hello World!")
End Sub

Sub sub3(text As String)
    MsgBox (text)
End Sub

Sub sub4(text1 As String, text2 As String)
    MsgBox (text1)
    MsgBox (text2)
End Sub

Upvotes: 1

Views: 593

Answers (1)

braX
braX

Reputation: 11755

Remove the parenthesis from places they do not belong.

Sub sub1()
   sub2
   sub2
   sub3 "Hello World!"
   sub4 "Hello World!", "Hello World! Again!"
End Sub

Sub sub2()
   MsgBox "Hello World!"
End Sub

Sub sub3(text As String)
   MsgBox text
End Sub

Sub sub4(text1 As String, text2 As String)
   MsgBox text1
   MsgBox text2
End Sub

See how in your example, VBA adds a space after the subroutine name and the parenthesis?

sub2 ()

That's a hint. What's happening is the two strings you are providing as arguments are getting evaluated first, resulting in a single argument that it tries to then pass to a subroutine that has 2 required arguments.

Functions that return something need the parenthesis to enclose the arguments and subroutines do not (cannot).

Upvotes: 1

Related Questions