首页 > 解决方案 > 编译错误:ByRef 参数类型不匹配:如何调用数组中的值

问题描述

在循环中,我想检查值是否在数组中,如果是,则跳到下一次迭代。

不过,我对数组的低理解阻碍了我:

我正在使用下面的函数(来自:Check if a value is in an array or not with Excel VBA)来查看该值是否在数组中。

Public Function IsInArray(Vtobefound As Long, arr As Variant) As Boolean
    Dim i
    For i = LBound(arr) To UBound(arr)
        If arr(i) = Vtobefound Then
            IsInArray = True
            Exit Function
        End If
    Next i
    IsInArray = False

End Function

但我下面的子仍然不起作用:

Sub CountCellstest()

    Dim i, k As Long
'   Dim iArray() As Single

    ReDim iArray(1 To 1) As Single

    For i = 1 To 3
        If IsInArray(i, iArray) Then 'ERROR HERE on the i

    GoTo next_iteration

        End If

            ReDim aArray(1 To 1) As Single
            iArray(UBound(iArray)) = 2
            ReDim Preserve iArray(1 To UBound(iArray) + 1) As Single
            'DO smth
            MsgBox "test"
next_iteration:
    Next i

End Sub

错误来自以下行:

If IsInArray(i, iArray) Then

我得到Compile error: ByRef arugment type mismatch 函数 IsInArray 需要很长,我在公式中放了很长,所以我不明白这个问题......有人能解释一下吗?

标签: arraysexcelvba

解决方案


常见的错误。您的i变量实际上是Variant不匹配的。您必须像这样单独键入所有变量:

Dim i As Long, k As Long

推荐阅读