Option Explicit Private WithEvents NewButton As CommandButton '通过使用WithEvents关键字声明一个对象变量为新的命令按钮 Private Sub Command1_Click() If NewButton Is Nothing Then Set NewButton = Controls.Add("VB.CommandButton", "cmdNew", Form1) '增加新的按钮cmdNew NewButton.Move Command1.Left + Command1.Width + 240, Command1.Top '确定新增按钮cmdNew的位置 NewButton.Caption = "动态添加的按钮" NewButton.Visible = True '显示该按钮 End If End SubPrivate Sub Command2_Click() If NewButton Is Nothing Then Exit Sub Else Controls.Remove NewButton Set NewButton = Nothing End If End SubPrivate Sub Form_Load()End SubPrivate Sub NewButton_click() MsgBox "这是动态增加的按钮,你可以单击“删除控件”按钮删除它", vbDefaultButton1, "Click" End Sub
Dim WithEvents Command1 As CommandButtonPrivate Sub Form_Load() Set Command1 = Controls.Add("vb.commandbutton", "command1", Form1) With Command1 .Move 0,0,200,100 .Caption = "New Button" .Visible = True End With End SubPrivate Sub Command1_Click() MsgBox "Click",vbOkOnly+vbInfomation,"Hint" Controls.Remove Command1 '移除控件 End Sub
1.使用控件数组,必须在设计时添加一个index为0的控件,程序中动态添加,例 : Load Command1(1) Command1(1).Left=Command1(0).Left+Command1(0).Width Command1(1).Visible=True 2.使用Controls集合的Add方法,例: Dim a As CommandButton Set a = Controls.Add("VB.CommandButton", "a2") a.Left = 0 a.Top = 0 a.Caption = "a2" a.Visible = True
Private WithEvents NewButton As CommandButton
'通过使用WithEvents关键字声明一个对象变量为新的命令按钮
Private Sub Command1_Click()
If NewButton Is Nothing Then
Set NewButton = Controls.Add("VB.CommandButton", "cmdNew", Form1)
'增加新的按钮cmdNew
NewButton.Move Command1.Left + Command1.Width + 240, Command1.Top
'确定新增按钮cmdNew的位置
NewButton.Caption = "动态添加的按钮"
NewButton.Visible = True
'显示该按钮
End If
End SubPrivate Sub Command2_Click()
If NewButton Is Nothing Then
Exit Sub
Else
Controls.Remove NewButton
Set NewButton = Nothing
End If
End SubPrivate Sub Form_Load()End SubPrivate Sub NewButton_click()
MsgBox "这是动态增加的按钮,你可以单击“删除控件”按钮删除它", vbDefaultButton1, "Click"
End Sub
Set Command1 = Controls.Add("vb.commandbutton", "command1", Form1)
With Command1
.Move 0,0,200,100
.Caption = "New Button"
.Visible = True
End With
End SubPrivate Sub Command1_Click()
MsgBox "Click",vbOkOnly+vbInfomation,"Hint"
Controls.Remove Command1 '移除控件
End Sub
:
Load Command1(1)
Command1(1).Left=Command1(0).Left+Command1(0).Width
Command1(1).Visible=True
2.使用Controls集合的Add方法,例:
Dim a As CommandButton
Set a = Controls.Add("VB.CommandButton", "a2")
a.Left = 0
a.Top = 0
a.Caption = "a2"
a.Visible = True