Reputation: 11
I have a stupid question, I always got the error type mismatch when I created a function which return a array. here are two simple example : if I don't declare the type when declaration: It will be compiled, but got the error after the function result
Function aa(c As Integer)
Dim arr(10)
Dim i As Integer
Dim k As Double
For i = 0 To 10
k = i ^ 2 / c + 1
arr(i) = CStr(k)
Debug.Print k
Next i
aa = arr
End Function
if i declare the type: it can't be compiled and will get the error directly
Function aa(c As Integer) as string()
Dim arr(10) as string
Dim i As Integer
Dim k As Double
For i = 0 To 10
k = i ^ 2 / c + 1
arr(i) = CStr(k)
Debug.Print k
Next i
aa = arr
End Function
Upvotes: 1
Views: 2225
Reputation: 19367
Your second version will work if you call it this way, using the same type:
Sub Testaa()
Dim result() As String
result = aa(4)
End Sub
Your first version will return a Variant
- any function (or variable) that isn't given a specific type will default to Variant
. So you need to store the return result in a Variant as well:
Sub Testaa()
Dim result As Variant
result = aa(4)
End Sub
It is preferable to use explicit types wherever possible.
Upvotes: 1