动态添加控件的方法除了通过数组的方法来实现
还有一种方法:假设两个按钮Commad1和Command2分别为添加按钮和删除按钮,代码实现如下
Option Explicit
Private WithEvents newbutton As CommandButton
' 添加控件
Private Sub Command1_Click()
If newbutton Is Nothing Then
Set newbutton = Controls.Add("vb.commandbutton", "cmdnew", Form1)
newbutton.Move Command1.Left + Command1.Width + 240, Command1.Top
newbutton.Caption = "动态添加的按钮"
newbutton.Visible = True
End If
End Sub
' 删除控件
Private Sub Command2_Click()
If newbutton Is Nothing Then
Exit Sub
Else
Controls.Remove newbutton
Set newbutton = Nothing
End If
End Sub
' 新添加的控件
Private Sub newbutton_click()
MsgBox "单击“删除控件”按钮删除它", vbDefaultButton1, "click"
End Sub