1

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?

2
  • 1
    Your casting an Array to a string, not a String to a string Commented Apr 9, 2015 at 9:38
  • You can assign the array(1) element to a string variable and pass that to the function, or declare Tx2 As Variant Commented Apr 9, 2015 at 9:44

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

why should I prefer to use Function myFunction(str As String, arr As Variant) As String>; why using Variant where I need a string?
1

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

1 Comment

Nope default is ByRef ;) I have to admit I use ByVal a lot (like for every arguments^^), not sure if it can be bad but it is widely useful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.