Option Explicit
Private WithEvents txt As TextBox
Private Sub Form_Load()
Dim i, j
For i = 1 To 5
'Set txt = Nothing
Set txt = Form1.Controls.Add("vb.textbox", "txt" & i)
With txt
    .Top = j + 400
    .Left = j + 400
    .Height = 400
    .Width = 400
    .Visible = True
End With
j = txt.Top
Next
End Sub
Private Sub txt_Click()
Select Case txt.Name
Case "txt1"
    MsgBox txt.Name
Case "txt2"
    MsgBox txt.Name
Case "txt3"
    MsgBox txt.Name
End Select这段代码是动态的在窗体上添加了5 个文本框
怎么样获取他们的事件

解决方案 »

  1.   

    http://community.csdn.net/Expert/topic/4327/4327982.xml?temp=.7222254
      

  2.   

    你已经Set了,说明在通用栏下拉列表里肯定已经产生txt选项,选择txt,这是不就出现
    Private Sub txt_Change()End Sub
    。。
      

  3.   

    因为你的txt对象所指向的对象不断在变,你应该定义跟你要添加控件数量一样多的txt对象,每个txt对象指向一个新加的控件并定义好事件!
      

  4.   

    Option Explicit
    Private txt As TextBox
    Private WithEvents txt1 As TextBox
    Private WithEvents txt2 As TextBox
    Private Sub Form_Load()
    Dim i, j
    For i = 1 To 2
    'Set txt = Nothing
    Set txt = Form1.Controls.Add("vb.textbox", "txt" & i)
    With txt
    .Top = j + 400
    .Left = j + 400
    .Height = 400
    .Width = 400
    .Visible = True
    End With
    j = txt.TopIf i = 1 Then
        Set txt1 = txt
    ElseIf i = 2 Then
        Set txt2 = txt
    End If
    Next
    End SubPrivate Sub txt1_LostFocus()
        MsgBox txt1.Name
    End SubPrivate Sub txt2_LostFocus()
        MsgBox txt2.Text
    End Sub