For循环条件下VB6类型不匹配

时间:2009-11-11 22:47:49

标签: vb6 for-loop type-mismatch

我一直试图找出为什么在下面的代码中,第三次通过循环我得到一个错误类型13不匹配时,正在评估“For lCount = 0 to maxCount”行。我原本以为问题在于从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

2 个答案:

答案 0 :(得分:1)

Public Function FindCodeIndex(Array() As String, ByVal MatchValue As String) As Long

    Dim index As Long
    Dim upper_bound As Long

    upper_bound= UBound(Array)
    MatchValue = UCase(MatchValue)

    For index = 0 To upper_bound
        If UCase(Array(index)) = MatchValue Then
            FindCodeIndex = index 
            Exit Function
        End If
    Next index 

    FindCodeIndex = -1

End Function

答案 1 :(得分:0)

该函数提到正在为ComboBox编写代码(您实际上是将List()方法中的每个项目复制到一个数组中并将其发送到您的函数吗?)。如果您使用标准VB ComboBox,这似乎有点过于复杂。只需使用以下代码:

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的速度要快得多。