' Déclarer en haut du UserForm
Private allProducts() As Variant ' tous les produits et prix
' --- À appeler lors de l'initialisation du UserForm ---
Private Sub UserForm_Initialize()
Dim ws As Worksheet
Dim tbl As ListObject
Dim arr As Variant
' Référence à la feuille et au tableau
Set ws = Workbooks("Donnees_Liste_Produits.xlsx").Sheets("Liste des services et produits")
Set tbl = ws.ListObjects("T_Produits")
' Charger le tableau en mémoire
arr = tbl.DataBodyRange.Value
allProducts = arr
' Initialiser ComboBox avec tous les produits
Me.ComboBox_Produit.List = arr
End Sub
' --- Filtrage rapide à la frappe ---
Private Sub ComboBox_Produit_Change()
Dim txt As String
txt = Me.ComboBox_Produit.Text
Dim arrFiltered() As Variant
Dim count As Long
Dim i As Long
' Compter les correspondances pour dimensionner le tableau
count = 0
For i = 1 To UBound(allProducts, 1)
If LCase(Left(allProducts(i, 1), Len(txt))) = LCase(txt) Then
count = count + 1
End If
Next i
If count = 0 Then Exit Sub
ReDim arrFiltered(1 To count, 1 To 2)
count = 0
For i = 1 To UBound(allProducts, 1)
If LCase(Left(allProducts(i, 1), Len(txt))) = LCase(txt) Then
count = count + 1
arrFiltered(count, 1) = allProducts(i, 1)
arrFiltered(count, 2) = allProducts(i, 2)
End If
Next i
' Désactiver events pour éviter boucles infinies
Application.EnableEvents = False
' Remplir ComboBox en une seule fois
Me.ComboBox_Produit.List = arrFiltered
Me.ComboBox_Produit.Text = txt
Me.ComboBox_Produit.SelStart = Len(txt)
' Afficher le prix si correspondance exacte
For i = 0 To Me.ComboBox_Produit.ListCount - 1
If LCase(Me.ComboBox_Produit.List(i, 0)) = LCase(txt) Then
Me.TextBox_Prix_Unit.Value = Format(Me.ComboBox_Produit.List(i, 1), "0.00 €")
Exit For
End If
Next i
Application.EnableEvents = True
End Sub