Private Sub CommandButton4_Click()
Dim ws As Worksheet
Dim tbl As ListObject
Dim Ind As Long
Dim i As Long
Dim found As Boolean
' Vérifier la saisie
If ComboBox1.ListIndex = -1 Then
MsgBox "Veuillez sélectionner une option dans la liste déroulante.", vbExclamation
Exit Sub
End If
If Trim(TextBox2.Text) = "" Then
MsgBox "Veuillez remplir la description dans TextBox2.", vbExclamation
Exit Sub
End If
Application.EnableEvents = False
Set ws = ActiveSheet
Set tbl = ws.ListObjects(1)
found = False
' Chercher si la valeur de TextBox2 existe déjà dans la colonne A
With tbl
For i = 1 To .ListRows.Count
If .DataBodyRange(i, 1).Value = TextBox2.Text Then
' Mise à jour des autres colonnes
.DataBodyRange(i, 2) = TextBox1.Text
.DataBodyRange(i, 3) = ComboBox1.Value
.DataBodyRange(i, 4) = Chr(168)
found = True
Exit For
End If
Next i
' Si non trouvé, on ajoute une nouvelle ligne
If Not found Then
Ind = .ListRows.Add.Index
.DataBodyRange(Ind, 1) = TextBox2.Text
.DataBodyRange(Ind, 2) = TextBox1.Text
.DataBodyRange(Ind, 3) = ComboBox1.Value
.DataBodyRange(Ind, 4) = Chr(168)
End If
' Trier le tableau sur la colonne A
.Sort.SortFields.Clear
.Sort.SortFields.Add Key:=.DataBodyRange.Columns(1), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
With .Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
' Message de confirmation
If found Then
MsgBox "Ligne mise à jour avec succès.", vbInformation
Else
MsgBox "Nouvelle ligne ajoutée avec succès.", vbInformation
End If
' Réinitialisation des champs
TextBox2.Text = ""
ComboBox1.ListIndex = -1
Application.EnableEvents = True
End Sub