12

I am trying to pass two string parameters to a Sub, but its not allowing me do that. The approach I have used is given below.

Sub callByValue( str1 As String, str2 As String)
MsgBox str1
MsgBox str2

End Sub

Calling Macros:

 Dim s1, s2 As String
 callByValue(s1,s2)

While calling callByvalue, it's throwing a compiler error.

Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
Samraan
  • 285
  • 3
  • 7
  • 14

2 Answers2

24

You need to remove the brackets

callByValue s1, s2

Also remember in VBA, When you say Dim s1, s2 As String only s2 will be declared as String and the first one will be declared as Variant

One more thing that I noticed was that you didn't assign the values of s1 and s2 before calling the sub. You will get a blank for both.

For example, do this.

Sub Sample()
    Dim s1 As String, s2 As String
    s1 = "Blah": s2 = "Blah Blah"
    callByValue s1, s2
End Sub
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
5

This is better definition for a ByVal call sub.

Sub callByValue(ByVal str1 As String, ByVal str2 As String)
  MsgBox str1
  MsgBox str2
End Sub

Sub sof20285505callByVal()
  Dim s1, s2 As String
  callByValue s1, s2
End Sub
jacouh
  • 8,473
  • 5
  • 32
  • 43
  • 1
    + 1 Now After your edit, I can upvote :P – Siddharth Rout Nov 29 '13 at 12:21
  • 1
    note that `dim s1, s2 as String` only declares the `s2` as String and `s1` as variant –  Nov 29 '13 at 12:28
  • @mehow, this is just the quality of my sub. All calling arguments are converted into string before passed into it... You can even call it with a Date type without error. – jacouh Nov 29 '13 at 12:30
  • implicitly converted. you have to be really careful about implicit conversion ( not THAT careful in VBA, but .Net languages is totally different story ). It's generally a good practice to declare the correct types for your variables –  Nov 29 '13 at 12:32
  • @mehow, I'm now for all variant type vars, as this is compatible for VBScript. – jacouh Nov 29 '13 at 12:37