james_elliot_62
james_elliot_62

Reputation: 39

Curious behavior of the Dim instruction in Microsoft Visual Basic

I am using VBA 7.1.1092 and I have the very strange (but I am probably missing something obvious) behavior. This is the code:

Function test(s As String) As String
    test = s
End Function
Function test2(p As String) As String
    Dim s As String
    Dim t As String
    s = p
    test2 = test(s)
End Function
Function test1(p As String) As String
    Dim s, t As String
    s = p
    test1 = test(s)
End Function

Function test2 does compile while the compilation of test1 fails on the instruction

test1=test(s)

with the error on s being "ByRef incompatible". I thought that the declarations in test1 and test2 were identical. So, what am I missing? Thanks in advance

Upvotes: 0

Views: 44

Answers (1)

Naveen Kumar
Naveen Kumar

Reputation: 2006

In VBA

Dim s, t As String

equivalent to:

Dim s as variant
Dim t as String

As type of s is omitted so by default it will be variant.

you will have to declare like this:

Dim s As String
Dim t As String

Upvotes: 3

Related Questions