Autobúsqueda en un combo de sólo lectura

 

Fecha: 24/Ago/98 (18/Ago/98)
Autor: Harvey
psoft@latino.net.co

Existen casos en que un ComboBox debe ser de solo lectura y queremos tenga la capacidad de autobusqueda. El caso común es en una consulta INNER JOIN, donde enlazamos una tabla de soporte para que suministre opciones al usuario, si permitimos que se escriba el ComboBox, puede suceder que cambiamos la tabla de soporte o nos ganamos errores de bloqueo del motor. Bien, en un ComboBox normalito (lo llamo cbx)

'
Private KeyChar  As String
'...

Private Sub cbx_KeyPress(KeyAscii As Integer)
    
    If KeyAscii = vbKeyReturn Then
       '//Skip to next control
       KeyAscii = 0
       SendKeys "{TAB}"
    Else
       KeyChar = Chr(KeyAscii)
       KeyAscii = 0
       SearchFirtsItem
    End If
End Sub

Private Sub cbx_KeyDown(KeyCode As Integer, Shift As Integer)
    DoEvents
    Select Case KeyCode
        Case vbKeyDown, vbKeyUp
        Case Else
             KeyCode = 0
    End Select
End Sub

Private Sub SearchFirtsItem()
    Dim i As Integer
    Dim n As Integer
    Static LastFound As Integer
    Static LastChar  As String
    
    If Not KeyChar = LastChar Then
       LastFound = -99
       LastChar = KeyChar
    End If
    n = 1
    With cbx
        For i = 0 To .ListCount - 1
            If StrComp(KeyChar, Left(.List(i), n), 1) = 0 Then
               If i > LastFound Then
                 .ListIndex = i
                 .Text = .List(.ListIndex)
                 .SelStart = 0
                 .SelLength = Len(.Text)
                  LastFound = i
                  Exit For
               End If
            End If
        Next
    End With
End Sub

P.e., si el usuaio teclea "C", entonces el ubica el primer item que empieza con "C", si se vuelque a dar "C", ubica el siguiente, y así.

ir al índice