genespos
genespos

Reputation: 3311

Type mismatch error passing a string to a function from an array (in VBA)

I have a code like this

Sub Test()
    Dim ArrayStrings()
    Dim T As String, myResult As String

    ArrayStrings = Array("String1", "String2", "String3", "String4", "String5", "StringN")
    T = "myString"

    myResult = myFunction(T, ArrayStrings(1))
End Sub

Function myFunction(Tx1 As String, Tx2 As String) As String
    'myCode
End Function

This get an error "type mismatch" on "ArrayStrings(1)"

I tryed different ways but the only working seems to be:

    myResult = myFunction(T, CStr(ArrayStrings(1)))

But it seems strange convert a string to a string ... isn't it? Is there any other way?

Upvotes: 1

Views: 976

Answers (2)

Gareth
Gareth

Reputation: 5243

Try casting your array as a variant and then pass that into the function.

Option Explicit

Sub Test()
    Dim arr() As Variant
    Dim str As String

    arr = Array("1", "2", "3")
    str = "Hello, world!"

    MsgBox myFunction(str, arr)
End Sub

Function myFunction(str As String, arr As Variant) As String
    Dim var As Variant
    Dim strOutput As String

    For Each var In arr
        strOutput = strOutput & " " & var
    Next var

    myFunction = strOutput
End Function

Upvotes: 2

R3uK
R3uK

Reputation: 14537

Indeed, converting a string to a string isn't glamourous...

Have you tried to use ByVal?

Function myFunction(Tx1 As String, ByVal Tx2 As String) As String

That should be enough

Upvotes: 1

Related Questions