通过阵列不匹配

时间:2016-04-04 10:38:54

标签: arrays vba mismatch

我将数组传递给函数后遇到问题。基本上我传递的数组包含一系列字符串,我想根据一些已知的值来检查。当我尝试这样做时,我得到了不匹配错误。

我尝试用msgbox诊断问题,但这让我更加困惑,因为在运行代码时弹出消息框并在数组中显示字符串。然后,当我单击OK时,即使msgbox命令刚刚显示正确的信息,显然也会出现错配错误。谁能告诉我为什么会出现不匹配?

错误:
Error

代码:

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

1 个答案:

答案 0 :(得分:1)

当第一次满足条件时,条件表达式会调用函数A2LConvert,但是它传递变量i(最初为0)。

例如,

    A2LConvert(i) = ...

实际上正在对A2LConvert进行函数调用,并将0作为“软件”变体传递。然后它尝试在该msgbox调用中访问0的第0个属性,这会触发类型不匹配错误。

通过实现中间数组(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