将事件处理程序应用于动态控制 [英] applying event handler to dynamic control

查看:42
本文介绍了将事件处理程序应用于动态控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户窗体,可以将 commandButton 动态放置到用户窗体上,但是我似乎无法正确设置动态事件处理程序:下面显示了有关如何设置动态按钮:

I have a userform that dynamically places a commandButton onto the user form but I can't seem to get the dynamic event handler set up properly: Below shows the code for how I have set up the dynamic button:

Set cButton = Me.Controls.Add("Forms.CommandButton.1")
With cButton
  .Left = 150
  .Top = 0
  .Width = 300
  .Height = 140
End With

我还在任何子程序或过程之外将 dim WithEvents cButton定义为Commandbutton ,然后终于有了动态按钮的事件处理程序,我现在只想输出一条消息:

I have also defined dim WithEvents cButton as Commandbutton outside of any sub or procedure and then finally I have the event handler for the dynamic button, which I simply want to output a message for now:

Private Sub cButton_Click()
   MsgBox "Dynamic Handler functioning correctly"
End Sub

现在,我能够为单个控件的动态事件创建事件处理程序,但是我正在创建多个控件,并且它们都具有相同的名称 cButton ,所以我将如何创建单个事件他们每个人的处理程序.下面显示了用于创建多个控件的代码:

Now that I am able to create event handlers for dynamic events for individual controls, however I am creating multiple controls and they all have the same name cButton so how would I be able to create individual event handlers for each of them. Below shows the code that is used to create the multiple controls:

If TextBox1 <> vbNullString Then
    For i = 1 To TextBox1.Value


    Set cButton = Me.Controls.Add("Forms.CommandButton.1")
        With cButton
            .Left = 150
            .Top = 0
            .Width = 300
            .Height = 140
        End With
  Next i
End IF

推荐答案

cButton 仅应声明一次:

Dim WithEvents cButton As CommandButton

Sub UserForm_Initialize()
    Set cButton = Me.Controls.Add("Forms.CommandButton.1")
    With cButton
      .Left = 150
      .Top = 0
      .Width = 300
      .Height = 140
    End With
End Sub

Private Sub cButton_Click()
   MsgBox "Dynamic Handler functioning correctly"
End Sub

这篇关于将事件处理程序应用于动态控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆