代码如下:
主要功能是在FORM上动态添加一个或多个控件。
1 Option Explicit 2 Dim oCtrl As Object 3 '使得控件可以响应事件 4 Dim WithEvents MyBtn As CommandButton 5 Private Sub Form_Load() 6 Dim i As Integer 7 '先在窗体上加载个Label1(0)的标签控件 8 For i = 1 To 3 9 Load Me.Label1(i) 10 Label1(i).Top = Label1(i - 1).Top + 2 * Label1(0).Height 11 Label1(i).Caption = "Label1(" & i & ")" 12 Label1(i).Visible = True 13 Next 14 'Debug.Print Me.Label1.Count 15 LoadControl 16 LoadControlWithEvents 17 End Sub 18 Private Sub LoadControl() 19 Set oCtrl = Controls.Add("VB.CommandButton", "Button1") 20 With oCtrl 21 .Caption = "不会响应事件的按钮" 22 .Width = 2000 23 .Left = 100 24 .Top = 200 25 .Visible = True '控件加载后默认为不可见,故此步骤至关重要! 26 End With 27 End Sub 28 Private Sub LoadControlWithEvents() 29 Set MyBtn = Controls.Add("VB.CommandButton", "Button2") 30 With MyBtn 31 .Caption = "我可以响应事件!" 32 .Width = 1800 33 .Left = 100 34 .Top = 700 35 .Visible = True 36 End With 37 End Sub 38 Private Sub MyBtn_Click() 39 MsgBox "我要移除动态加载的控件了!" 40 Me.Controls.Remove "Button1" 41 Me.Controls.Remove "Button2" 42 End Sub