2017-08-02 2 views
1

Je pourrais vraiment utiliser de l'aide à ce sujet. J'ai lu environ 60+ sites Web et soit ne pas cliquer (jeu de mots), ou c'est incorrect pour mon application. Voici le résumé:Comment utiliser un bouton dynamique dans Userform VBA

Objectif: Utilisez un bouton "Envoyer" qui a été créé dynamiquement dans un Userform pour copier la légende d'un bouton OptionButton dans une cellule dynamique de la feuille de calcul, puis désactivez/fermez le Userform. Contexte: Le formulaire utilisateur est appelé à partir d'un changement de colonne dans la feuille de calcul.

Voici un extrait du code utilisé pour appeler le userform:

Private Sub Worksheet_Change(ByVal Target As Excel.Range) 
Dim lastRow As Long 

    With Worksheets("Test") 
     lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 
    End With 
    With Target 
     If .Count > 1 Then Exit Sub 
     If Not Intersect(Range("B1:B" & lastRow), .Cells) Is Nothing Then 
      Application.EnableEvents = False 
      If IsEmpty(.Value) Then 
       .Offset(0, 1).ClearContents 
      Else 
       With .Offset(0, 1) 
        .NumberFormat = "mmm dd yyyy hh:mm:ss" 
        .Value = Now 
        UserForm1.Show 
       End With 
      End If 
      Application.EnableEvents = True 
     End If 
    End With 

End Sub 

Après la Userform apparaît, initialisées. Il extrait d'une liste sur la feuille de calcul pour indiquer le nombre de boutons d'option, leurs légendes et les dimensions de chaque élément dans Userform. Le code qui est ceci:

Sub UserForm_Initialize() 

Dim HLastRow As Integer 
Dim NoOfExplanations As Integer 
Dim TopPixels As Integer 
Dim UserFormHeight As Integer 
Dim UserFormWidth As Integer 
Dim Opt As Variant 
Dim i As Integer 
Dim ExplanationRow As Integer 
Dim lbl As MSForms.Label 
Dim LabelCap As String 
Dim btn As CommandButton 
Dim OtherInput As MSForms.TextBox 
Dim Margins As Integer 

    With Worksheets("Test") 
     HLastRow = .Cells(.Rows.Count, "H").End(xlUp).Row 
    End With 

NoOfExplanations = Application.WorksheetFunction.CountA(Worksheets("Test").Range("H2:H" & HLastRow)) 
Margins = 20 

LabelCap = "You have chosen a non sequential row for your team/subteam. Please select an explanation below before you are able to proceed" 
UserFormWidth = Len(LabelCap) * 2 
TopPixels = (18 * 2) 
UserFormHeight = TopPixels + 80 + (20 * NoOfExplanations) 

    With UserForm1 
     .Width = UserFormWidth + 40 
     .Height = UserFormHeight 
    End With 

    Set lbl = UserForm1.Controls.Add("Forms.Label.1") 
    With lbl 
     .Top = 10 
     .Left = 20 
     .Height = 20 
     .Width = UserFormWidth - 20 
     .Caption = LabelCap 
    End With 

ExplanationRow = 2 
For i = 1 To NoOfExplanations 

    Set Opt = UserForm1.Controls.Add("Forms.OptionButton.1", "OptionButton" & i, True) 

    Opt.Caption = Worksheets("Test").Cells(ExplanationRow, 8).Value 

    If Worksheets("Test").Cells(ExplanationRow, 8).Value = "Other" Then 
     Set OtherInput = UserForm1.Controls.Add("Forms.TextBox.1") 
     With OtherInput 
      .Top = TopPixels 
      .Width = UserFormWidth - (Len(Worksheets("Test").Cells(ExplanationRow, 8).Value) * 11) 
      .Left = UserFormWidth - (UserFormWidth - (Len(Worksheets("Test").Cells(ExplanationRow, 8).Value) * 11)) 
      .Height = 18 
     End With 
    End If 

    If Len(Worksheets("Test").Cells(ExplanationRow, 8).Value) > 45 Then 
     Opt.Width = UserFormWidth - 10 
     Opt.Height = 36 
     Opt.Left = 18 

     Opt.Top = TopPixels 
     TopPixels = TopPixels + 38 
    End If 

    If Len(Worksheets("Test").Cells(ExplanationRow, 8).Value) <= 45 Then 
     Opt.Width = UserFormWidth - 10 
     Opt.Height = 18 
     Opt.Left = 18 

     Opt.Top = TopPixels 
     TopPixels = TopPixels + 20 
    End If 
    ExplanationRow = ExplanationRow + 1 
Next i 

    Set btn = UserForm1.Controls.Add("Forms.CommandButton.1") 
    With btn 
     .Top = TopPixels 
     .Width = 40 
     .Left = ((UserFormWidth + 40)/2) - 20 
     .Height = 20 
     .Caption = "Submit" 
     .Name = btn 
    End With 
End Sub 

Question: Alors, comment puis-je obtenir le BTN créé ici dans le Userform à la fois copier la légende OptionButton sélectionnée dans la cellule dynamique, puis clair/fermer le Userform?

Je sais que c'est un étirement, mais j'essaie de remplir la cellule qui est à deux colonnes de la cellule "Cible" qui déclenche l'Userform à ouvrir. Le code remplit la date/heure actuelle dans le .Offset (0, 1) dans le Worksheet_Change coupé, mais est-il un moyen de placer la légende OptionButton dans la cellule à .Offset (0, 2)? Je suis encore assez nouveau à VBA et cette chose est vraiment coller une épine en moi.

Je serai incroyablement reconnaissant pour toute aide à ce sujet.

Merci! Joe

Répondre

1

La modification de votre variable btn en variable de niveau classe et en utilisant WithEvents vous permet d'accéder aux événements de boutons dynamiques.

Private WithEvents btn As CommandButton 

Private Sub btn_Click() 
    Dim ctrl As Control 
    For Each ctrl In Me.Controls 
     If TypeName(ctrl) = "OptionButton" Then 
      If ctrl.Object.Value Then 
       MsgBox ctrl.Object.Caption 
      End If 
     End If 
    Next 
End Sub 

enter image description here

+0

Merci beaucoup Thomas! Désolé si c'est une question stupide, mais comment changer le 'btn' à une variable de niveau de classe? J'ai mis le code exactement comme vous l'avez dans le fichier GIF, mais ça ne fonctionne toujours pas, alors je pense que je manque ce morceau. –

+0

Les variables de classe sont déclarées en dehors de toute sous-routine de préférence en haut du module. Assurez-vous que vous n'avez pas une variable avec le même nom déclaré dans votre sous-routine. –

+0

Ok, génial. Je l'ai fait fonctionner. C'est un bon pas dans la bonne direction. Merci beaucoup pour l'aide de Thomas! –