2

我一直试图找出为什么在下面的代码中,第三次通过循环我在评估“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
4

2 回答 2

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
于 2009-11-11T22:56:43.073 回答
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 会更快更小。

于 2009-11-19T03:31:58.963 回答