XL 2019 Recherche d'un nom dans une listview à l'aide d'un textbox

JFLulu

XLDnaute Nouveau
Bonjour à toutes et tous,
j'ai un control listview chargé avec 3000 clients, provenant de ma feuille "TableClient". je souhaite rechercher un nom X ou Y en frappe intuitive, (style google) à travers un textebox.
je souhaite faire cette recherche directement sur la listview donc sur l' ltem considéré en l'occurrence le nom (Item.SubItems(3) = Worksheets("Tableclient").Cells(i, 3)

je suis un peu perdu, merci par avance de votre aide .
Cordialement
 

Xtian_Québec

XLDnaute Occasionnel
Salut JFLulu
J'utilise aussi des listview et pour rechercher rapidement un client dans ma liste, j'ajoute un champ de recherche au-dessus de chacune des colonnes et lorsque je tape des lettres dans ce champ, ma requête met automatiquement à jour ma liste.

Mon textbox de recherche se nomme txbRechercheClientNom

J'ai le code suivant qui active la mise à jour chaque fois que la valeur change dans ce textbox
Private Sub txbRechercheClientNom_Change()
'AFFICHER RECHERCHE CLIENT
getClient
End Sub

Voici ma routine qui met à jour ma recherche
VB:
Sub getClient()
    Dim lvItem As ListItem
    Dim strSearchValue As String
    Dim intSearch As Integer
    
    'Effacer valeurs précédentes
    Ugar.lvwClient.ListItems.Clear
    intSearch = 0
    
    'Réinitialiser SQL
    gstrSQL = vbNullString
    gstrSQL = " SELECT * FROM Client"
 
    'RECHERCHE NOM CLIENT
    If Ugar.txbRechercheClientNom <> vbNullString Then
        gstrSQL = gstrSQL & " AND [Nom] LIKE '%" & Ugar.txbRechercheClientNom & "%'"
    End If
 
   'Obtenir données des clients
    'Gestion des erreurs
    On Error GoTo ErrorRecSet
    
    'Ouverture du RecSet
    Set gstrRecSet = New ADODB.Recordset
    gstrRecSet.Open gstrSQL, gstrObjCon, adOpenDynamic, adLockOptimistic, adCmdText
    
    Do While Not gstrRecSet.EOF
        'Adds rows and load the file in the list
        Set lvItem = Ugar.lvwClient.ListItems.Add(, , Format(GetDB(gstrRecSet.Fields("NoPlaque"), xlText)))
            With lvItem
                .ListSubItems.Add , , Format(GetDB(gstrRecSet.Fields("Marque"), xlText))
                .ListSubItems.Add , , Format(GetDB(gstrRecSet.Fields("NoClient"), xlText), "0000")
                .ListSubItems.Add , , Format(GetDB(gstrRecSet.Fields("Nom"), xlText))
                .ListSubItems.Add , , Format(GetDB(gstrRecSet.Fields("Prenom"), xlText))
                .ListSubItems.Add , , Format(GetDB(gstrRecSet.Fields("Statut"), xlText))
                .ListSubItems.Add , , Format(GetDB(gstrRecSet.Fields("Adresse"), xlText))
                .ListSubItems.Add , , Format(GetDB(gstrRecSet.Fields("Appt"), xlText))
                .ListSubItems.Add , , Format(GetDB(gstrRecSet.Fields("Ville"), xlText))
                .ListSubItems.Add , , Format(GetDB(gstrRecSet.Fields("CodePostal"), xlText))
                .ListSubItems.Add , , Format(GetDB(gstrRecSet.Fields("TelMaison"), xlText))
                .ListSubItems.Add , , Format(GetDB(gstrRecSet.Fields("TelBureau"), xlText))
                .ListSubItems.Add , , Format(GetDB(gstrRecSet.Fields("TelPosteBureau"), xlText))
                .ListSubItems.Add , , Format(GetDB(gstrRecSet.Fields("TelCellulaire"), xlText))
                .ListSubItems.Add , , Format(GetDB(gstrRecSet.Fields("Email"), xlText))
            End With
        gstrRecSet.MoveNext
    Loop
    'Fermeture du RecSet
    gstrRecSet.Close
    Set gstrRecSet = Nothing
    Exit Sub
ErrorRecSet:
    MsgBox "Une erreur est survenue lors de la récupération des données pour ce client." & vbCrLf & vbCrLf & "Veuillez aviser l'assistance technique pour vérifier ce problème." & vbCrLf & "Merci.", vbCritical, "Erreur d'exécution"
End Sub

Lorsque je tape "D" dans le textbox, tous les noms de clients avec la lettre D s'affiche
Si je continue de taper "DU" dans le textbox, tous les noms de clients avec la lettre DU s'affiche
Si je continue de taper "DUB" dans le textbox, tous les noms de clients avec la lettre DUB s'affiche
et ainsi de suite...
Cette logique peut s'appliquer à toutes les colonnes. moi, j'ai des champs de recherche (filtre) pour la plupart de mes colonnes au-dessus de mon listview. Mon fichier est trop volumineux pour le partager mais je te joint une image pour t'aider à comprendre ce qui se passe avec mes textbox.


Au fur et à mesure que j'entre des lettres dans mon textbox, la liste se précise...
J'espère que ce code t'aidera à ajuster ton fichier.

Xtian_Quebec
 

Pièces jointes

  • RechercheAutomatique.JPG
    RechercheAutomatique.JPG
    67.9 KB · Affichages: 93

Xtian_Québec

XLDnaute Occasionnel
Pas de problème...si je peux aider, ça me fait plaisir...même à 18h55 le soir ;)
J'avais oublé d'infiqué que j'utilise un module avec les "public variable" afin d'éviter de les répéter dans tous les codes où j'en ai besoin.
Dans le code que je t'ai partagé, la variable gstrSQL est définie dans mon module VARIABLE.
Public gstrSQL as string

Tu peux utiliser dim gstrSQL as string au début de la routine si tu as un problème avec le code.
J'utilise également des variables pour ma base de données...même logique...
Finalement, j'utilise une "function" GetDB pour récupérer les données de ma base de données.
Voici cette fonction si jamais tu veux l'utilisé.

VB:
Public Function GetDB(ByVal objField As ADODB.Field, intType As Integer, Optional varDef As Variant) As Variant
    Dim strPt1 As String
    Dim strPt2 As String

    If IsNull(objField.Value) Then
        If IsMissing(varDef) Then
            Select Case intType
                Case xlText
                    GetDB = ""
                Case xlNumber
                    GetDB = 0
                Case xlDate
                    GetDB = Date
                Case vbBoolean
                    GetDB = False
            End Select
        Else
            GetDB = varDef
        End If
    ElseIf LenB(objField.Value) = 0 Then
        If IsMissing(varDef) Then
            Select Case intType
                Case xlText
                    GetDB = ""
                Case xlNumber
                    GetDB = 0
                Case xlDate
                    GetDB = Date
                Case vbBoolean
                    GetDB = False
            End Select
        Else
            GetDB = varDef
        End If
    Else
        Select Case intType
            Case xlText
                GetDB = objField.Value
            Case xlNumber
                If Len(objField.Value) > 3 Then
                    strPt1 = CStr(objField.Value)
                    Select Case Application.DecimalSeparator
                        Case "."
                            If InStr(CStr(objField.Value), ",") > 0 Then
                                strPt1 = Strings.Left(objField.Value, InStr(CStr(objField.Value), ",") - 1)
                                strPt2 = Right(objField.Value, Len(objField.Value) - InStr(CStr(objField.Value), ","))
                                GetDB = UVal(strPt1 & "." & strPt2)
                            Else
                                GetDB = objField.Value
                            End If
                        Case ","
                            If InStr(CStr(objField.Value), ".") > 0 Then
                                strPt1 = Strings.Left(objField.Value, InStr(CStr(objField.Value), ".") - 1)
                                strPt2 = Right(objField.Value, Len(objField.Value) - InStr(CStr(objField.Value), "."))
                                GetDB = UVal(strPt1 & "." & strPt2)
                            Else
                                GetDB = objField.Value
                            End If
                        Case Else
                            GetDB = objField.Value
                    End Select
                Else
                    GetDB = objField.Value
                End If
            Case xlDate
                GetDB = objField.Value
            Case vbBoolean
                GetDB = objField.Value
        End Select

    End If
End Function

Elle semble un peu complexe mais si tu la suis pas à pas, tu comprendras facilement son fonctionnement.
Je présume que tu es OK avec le reste mais si tu as des questions, n'hésites pas.
Bonne continuité...

Xtian_Quebec
 

BOISGONTIER

XLDnaute Barbatruc
Repose en paix
Bonjour,

Exemple


VB:
Option Compare Text
Dim f, Tbl(), Ncol
Private Sub UserForm_Initialize()
   Set f = Sheets("bd")
   Tbl = f.Range("A2:P" & f.[A65000].End(xlUp).Row).Value
   Ncol = UBound(Tbl, 2)
   '---listview
    With Me.ListView1
        With .ColumnHeaders
           .Clear
           For k = 1 To Ncol
             .Add , , f.Cells(1, k), f.Columns(k).Width * 1
           Next k
        End With
        .Gridlines = True
        .View = lvwReport
        ligne = 1
        For i = 1 To UBound(Tbl)
          .ListItems.Add , , Tbl(i, 1)
          For k = 2 To Ncol
            .ListItems(ligne).ListSubItems.Add , , Tbl(i, k)
          Next k
          ligne = ligne + 1
        Next i
    End With
End Sub

Private Sub TextBoxRech_Change()
    ligne = 1
    With Me.ListView1
     .ListItems.Clear
     For lig = 1 To UBound(Tbl)
      If Tbl(lig, 4) Like "*" & Me.TextBoxRech & "*" Then
       .ListItems.Add , , Tbl(lig, 1)
       For k = 2 To Ncol
          .ListItems(ligne).ListSubItems.Add , , Tbl(lig, k)
       Next k
       ligne = ligne + 1
      End If
    Next lig
    Me.TextBox1 = .ListItems.Count
  End With
End Sub

Boisgontier
 

Discussions similaires

Statistiques des forums

Discussions
311 725
Messages
2 081 939
Membres
101 844
dernier inscrit
pktla