Comment réunir UserForm et Module de classe en un seul module exportable?
Bonjour,
Soit un UserForm (UserForm1) comportant un nombre "dynamique" de boutons.
J'ai dans ce projet besoin :
- d'un module Userform :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| Private Sub UserForm_Initialize()
Dim Obj As Control
Dim i As Integer
Dim Cl As Classe1
Set Collect = New Collection
For i = 1 To 7
Set Obj = Me.Controls.Add("forms.CommandButton.1")
With Obj
.Name = "Bouton" & i
.Object.Caption = "Bouton " & i
.Width = 100
.Height = 30
.Left = 20
.Top = .Height * (i - 1) + 5
End With
Set Cl = New Classe1
Set Cl.Bouton = Obj
Collect.Add Cl
Next i
With Me
.Height = Obj.Height + Obj.Top + (5 * (i - 2))
.Width = (Obj.Left * 2) + Obj.Width
End With
Set Obj = Nothing
End Sub |
- d'un module standard :
Code:
1 2 3
| Option Explicit
Public Collect As Collection |
- d'un module de classe (Classe1) :
Code:
1 2 3 4 5 6 7
| Option Explicit
Public WithEvents Bouton As MSForms.CommandButton
Private Sub Bouton_Click()
MsgBox Bouton.Name
End Sub |
Très efficace, tout fonctionne.
Mais, mon but est d'exploiter cet UserForm dans de nombreux projets Excel.
Je souhaite donc n'avoir qu'un seul module à exporter et importer.
Dans un premier temps, j'ai songé à intégrer le module de classe dans l'Userform de cette manière :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| Option Explicit
Public WithEvents Bouton As MSForms.CommandButton
Private Sub Bouton_Click()
MsgBox Bouton.Name
End Sub
Private Sub UserForm_Initialize()
Dim Obj As Control
Dim i As Integer
Dim Cl As Classe1
Set Collect = New Collection
For i = 1 To 7
Set Obj = Me.Controls.Add("forms.CommandButton.1")
With Obj
.Name = "Bouton" & i
.Object.Caption = "Bouton " & i
.Width = 100
.Height = 30
.Left = 20
.Top = .Height * (i - 1) + 5
End With
Set Obj = Me.Bouton
Next i
With Me
.Height = Obj.Height + Obj.Top + (5 * (i - 2))
.Width = (Obj.Left * 2) + Obj.Width
End With
Set Obj = Nothing
End Sub |
Mais cela ne fonctionne pas, une variable With Events ne pouvant être un tableau... Dans le code ci-dessus seul le dernier bouton réagit. Normal!
Je pourrais, bien entendu, déclarer chaque bouton dans une variable With Events :
Code:
1 2 3 4 5 6 7
| Public WithEvents Bouton1 As MSForms.CommandButton
Public WithEvents Bouton2 As MSForms.CommandButton
Public WithEvents Bouton3 As MSForms.CommandButton
Public WithEvents Bouton4 As MSForms.CommandButton
Public WithEvents Bouton5 As MSForms.CommandButton
Public WithEvents Bouton6 As MSForms.CommandButton
Public WithEvents Bouton7 As MSForms.CommandButton |
Mais le but est que cela soit réellement dynamique.
Avez-vous donc une solution pour "intégrer" ces trois modules en un seul?
Peut être créer l'userfom depuis le module de classe... Mais je n'y arrive pas...
Merci d'avance