Search code examples
arraysvbamismatch

Passed Array Mismatch


I'm having problems with an array after passing it into a function. Basically I'm passing an array which contains a series of strings that I want to check against some know values. When I try and do this I get the mismatch error.

I tried to diagnose the problem with the msgbox but this has confused me further as when running the code the message box pops up and shows the string the in the array. Then when I click OK the msgbox command apparently errors with a mismatch fault even though it has just displayed the correct infomation. Can anyone tell me why there would be a mismatch?

Error:
Error

Code:

Public Function A2LConvert(ByRef Software As Variant) As Variant

For i = 0 To 6
MsgBox (Software(i))
    If Software(i) = "A" Then 'Or "A1" Then
        A2LConvert(i) = "A.txt"
    ElseIf Software(i) = "C" Then
        A2LConvert(i) = "C.txt"
    ElseIf Software(i) = "B" Then
        A2LConvert(i) = "B.txt"
    ElseIf Software(i) = "D" Then
        A2LConvert(i) = "D.txt"
    ElseIf Software(i) = "E" Then
        A2LConvert(i) = "E.txt"
    ElseIf Software(i) = "F" Then
        A2LConvert(i) = "F.txt"
    ElseIf Software(i) = "G" Then
        A2LConvert(i) = "G.txt"
    Else
        A2LConvert(i) = ""
    End If

Next i

End Function

Solution

  • When a condition is met for the first time, your conditional expression is recalling the function A2LConvert, however it is passing variant i (initially 0).

    For example,

        A2LConvert(i) = ...
    

    is actually making a function call to A2LConvert and passing 0 as the 'Software' variant. It then attempts to access the zeroth property of 0 in that msgbox call, which triggers the type mismatch error.

    The behaviour that (I think) you want can be achieved by implementing an intermediary array (tempAr):

    Public Function A2LConvert(ByRef Software As Variant) As Variant
    
    Dim tempAr(6) As Variant
    
    For i = 0 To 6
    MsgBox Software(i)
        If Software(i) = "A" Then 'Or "A1" Then
            tempAr(i) = "A.txt"
        ElseIf Software(i) = "C" Then
            tempAr(i) = "C.txt"
        ElseIf Software(i) = "B" Then
            tempAr(i) = "B.txt"
        ElseIf Software(i) = "D" Then
            tempAr(i) = "D.txt"
        ElseIf Software(i) = "E" Then
            tempAr(i) = "E.txt"
        ElseIf Software(i) = "F" Then
            tempAr(i) = "F.txt"
        ElseIf Software(i) = "G" Then
            tempAr(i) = "G.txt"
        Else
            tempAr(i) = ""
        End If
    
    Next i
    
    A2LConvert = tempAr
    
    End Function