1

My question is related to this one. I created a class:

Public WithEvents btn As MSForms.CommandButton
    Private Sub btn_Click()
    MsgBox "Hello"
End Sub

The code below works well. I mean 10 buttons are displayed and after they are clicked, the message-box appears.

Dim collBtns As Collection

Public Sub UserForm_Initialize()

Dim btn As CommandButton
Dim btnH As cButtonHandler
Set collBtns = New Collection

For k = 1 To 10
    Set btn = testform.Controls.Add("Forms.CommandButton.1", True)
    With btn
        .Caption = "Title"
        .Left = 80
        .Width = 80
        .Top = 20 * k

        Set btnH = New cButtonHandler
        Set btnH.btn = btn
        collBtns.Add btnH
    End With
Next k

End Sub 

However, I need to use this procedure inside another procedure. The code below does not work.

Dim collBtns As Collection

Public Sub UserForm_Initialize()
Call Click100
End Sub

Public Sub Click100()

Dim btn As CommandButton
Dim btnH As cButtonHandler
Set collBtns = New Collection

For k = 1 To 10
    Set btn = testform.Controls.Add("Forms.CommandButton.1", True)
    With btn
        .Caption = "Title" 
        .Left = 80
        .Width = 80
         .Top = 20 * k

        Set btnH = New cButtonHandler
        Set btnH.btn = btn
        collBtns.Add btnH
    End With
Next k

End Sub
Community
  • 1
  • 1
  • It's a scoping problem, I think. Try moving `Dim btnH As cButtonHandler` to the top of your Userform module, with the Collection declaration. Right now the class is going out of scope when the inner routine ends. – Doug Glancy Jun 26 '15 at 17:34
  • Is `cButtonHandler` your class?? - What is the problem with your code? `Where` is the problem, exaclty? It seems fine....do you have `testform` accessible where `Click100` is defined? Is your class accessible where `Click100` is defined? – Daniel Möller Jun 26 '15 at 17:44
  • Sorry, it was a silly mistake. I should have inserted `testform2` rather than `testform`. Now it's OK. – Dominik Korniluk Jun 29 '15 at 08:34

0 Answers0