Results 1 to 2 of 2

Thread: events and dynamic control in Excel VBA

  1. #1

    Thread Starter
    Fanatic Member ZeBula8's Avatar
    Join Date
    Oct 2002
    Posts
    548

    events and dynamic control in Excel VBA

    i can dynamically add commandbuttons to an excel form. And then I use WithEvents.

    I just cannot get the Click event to fire. I can see the list of events in the dropdown for my new control that will be added to the control collection but it won't fire.

    Any ideas why?

    Code:
    Dim WithEvents cmdAdmit As CommandButton
    
    Private Sub UserForm_Click()
    Set mycmd = Controls.Add("Forms.CommandButton.1", "cmdAdmit", Visible)
        mycmd.Left = 10
        mycmd.Top = 100
        mycmd.Width = 175
        mycmd.Height = 20
        mycmd.Caption = "Admit"
    End Sub
    
    Private Sub cmdAdmit_Click()
        MsgBox "testing 1-2-3"
    End Sub

  2. #2
    Evil Genius alex_read's Avatar
    Join Date
    May 2000
    Location
    Espoo, Finland
    Posts
    5,538
    You need to set the same variable name as is declared, i.e. :
    VB Code:
    1. Private WithEvents cmdAdmit As msforms.CommandButton
    2.  
    3. Private Sub UserForm_Click()
    4.     Set cmdAdmit = Controls.Add("Forms.CommandButton.1", _
    5.     "cmdAdmit", True)
    6.    
    7.     With cmdAdmit
    8.         .Left = 10
    9.         .Top = 100
    10.         .Width = 175
    11.         .Height = 20
    12.         .Caption = "Admit"
    13.     End With
    14. End Sub
    15.  
    16. Public Sub cmdAdmit_Click()
    17.     MsgBox "testing 1-2-3"
    18. End Sub

    Please rate this post if it was useful for you!
    Please try to search before creating a new post,
    Please format code using [ code ][ /code ], and
    Post sample code, error details & problem details

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width