For循环条件中的VB6类型不匹配

For循环条件中的VB6类型不匹配,vb6,for-loop,type-mismatch,Vb6,For Loop,Type Mismatch,我一直在试图找出为什么在下面的代码中,在第三次通过循环时,当对行“For lCount=0 to maxCount”求值时,我得到一个错误类型13不匹配。我原本以为问题在于从vArray获取值,但测试显示它是由“For”行触发的。我不知道在循环处理过程中类型会如何变化。谢谢 Public Function FindCodeIndex(vArray As Variant, MatchValue As String) As Integer ''This function locate

我一直在试图找出为什么在下面的代码中,在第三次通过循环时,当对行“For lCount=0 to maxCount”求值时,我得到一个错误类型13不匹配。我原本以为问题在于从vArray获取值,但测试显示它是由“For”行触发的。我不知道在循环处理过程中类型会如何变化。谢谢

    Public Function FindCodeIndex(vArray As Variant, MatchValue As String) As Integer
    ''This function locates a value in a combo box returning the index or -1 if not found
    Dim lCount As Long
    Dim maxCount As Long
    Dim arrayStr As String


    On Error GoTo ErrorHandler

    maxCount = UBound(vArray)


    For lCount = 0 To maxCount
    arrayStr = vArray(1, lCount)

        If UCase$(arrayStr) = UCase$(MatchValue) Then
            FindCodeIndex = Int(lCount)
            Exit Function
        End If
    Next lCount

    FindCodeIndex = -1

    Exit Function


ErrorHandler:

MsgBox "Unexpected error in frmComment::FindCodeIndex()" & vbCrLf & _
           "Error Code: " & CStr(Err.Number) & " Error Desc: " & Err.Description

函数提到代码是为一个组合框编写的(您是否真的将List()方法中的每个项复制到一个数组中并将其发送给函数?)。如果您使用的是标准的VB组合框,那么这似乎有点过于复杂。只需使用以下代码:

Private Declare Function SendMessage Lib "User32.dll" Alias "SendMessageA" (ByVal hWnd As Long, ByVal uMsg As Long, ByRef wParam As Any, ByRef lParam As Any) As Long

Private Const CB_FINDSTRINGEXACT As Long = &H158

Public Function FindCodeIndex(ByRef cmb As ComboBox, ByRef sMatchValue As String) As Long
'This function locates a value in a combo box returning the index or -1 if not found

    FindCodeIndex = SendMessage(cmb.hWnd, CB_FINDSTRINGEXACT, ByVal -1, ByVal sMatchValue

End Function

在这种情况下,使用Windows API会更快、更小。

您不会将
arrayStr
赋值给任何值。你确定这不是问题吗?向arrayStr添加了分配(从内存,而不是现在的工作PC)。测试显示循环在第三遍的For语句中失败。Tim,你能使用“局部变量”窗口查看第三遍使用的数组中的数据,并编辑你的问题以包含此信息。VB肯定不喜欢这种解决方案,抱怨没有定义数组()。最近的测试表明,设置Long=-1也会抛出一个错误(?)@Timbuck
Array
在VB6中不是有效的标识符,因为它与内置的
Array
函数冲突。正是因为如此,我不确定为什么Chaospanion将此代码放在这里,除非我遗漏了什么。这对我来说有点不好的评论,也与十年前另一个开发人员做出的错误决策有关。实际上,我拥有的是一个包含两行的数组,第一行是代码描述列表,第二行是关联的代码列表。上面的函数在数组中查找匹配的代码值,并将combobox listindex=设置为找到该项的数组的位置。组合框显示代码描述。
Private Declare Function SendMessage Lib "User32.dll" Alias "SendMessageA" (ByVal hWnd As Long, ByVal uMsg As Long, ByRef wParam As Any, ByRef lParam As Any) As Long

Private Const CB_FINDSTRINGEXACT As Long = &H158

Public Function FindCodeIndex(ByRef cmb As ComboBox, ByRef sMatchValue As String) As Long
'This function locates a value in a combo box returning the index or -1 if not found

    FindCodeIndex = SendMessage(cmb.hWnd, CB_FINDSTRINGEXACT, ByVal -1, ByVal sMatchValue

End Function