'menu contextuel avec le onAction redirigigé dans des pseudo events dans le userform
'Auteur @jurassic pork
'remastered par @patricktoulon(sub classing intra userform)
Option Explicit
Public WithEvents ContextMenu_Add As CommandBarButton
Public WithEvents ContextMenu_Remove As CommandBarButton
Public LeMe As Object
Const twips = 15
'event bouton ajouter
Private Sub ContextMenu_Add_Click(ByVal Ctrl As Office.CommandBarButton, CancelDefault As Boolean)
Dim elem
elem = InputBox("Entrez votre élément :", "Ajouter élément", , _
LeMe.Left / 0.75 * twips, _
(LeMe.Top + LeMe.Height) / 0.75 * twips)
If elem <> "" Then LeMe.ListBox1.AddItem elem
End Sub
'Events bouton supprimer
Private Sub ContextMenu_Remove_Click(ByVal Ctrl As Office.CommandBarButton, CancelDefault As Boolean)
With LeMe.ListBox1
If .ListIndex >= 0 Then .RemoveItem .ListIndex
End With
End Sub
Private Sub ListBox1_Mouseup(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
'le menu est généré au click droite dans la listebox
' et est supprimé immediatement au momment ou il disparait
Dim Bar
If Button = 2 Then 'si bouton droite
Set Bar = CommandBars.Add("menuf", msoBarPopup, , True)
'creation bouton dans menu
With Bar.Controls.Add(msoControlButton): .Caption = "Ajouter": End With
With Bar.Controls.Add(msoControlButton): .Caption = "Suprimer": End With
'classemment intra classe userform
With UserForm1
Set .ContextMenu_Add = Bar.Controls(1)
Set .ContextMenu_Remove = Bar.Controls(2)
Set LeMe = Me
End With
Bar.ShowPopup
CommandBars("menuf").Delete
End If
Exit Sub
CommandBars("menuf").Delete
On Error GoTo 0
End Sub