通过Add方法实现 Add方法在Controls集合中添加一个控件并返回一个对控件的引用。Add方法的语法为:Object.Add(ProgID,Name,Container)其中Object为要添加元素的集合,ProgID为标示的字符串.可通过对象浏览器来确定,例如,CommandButton控件的ProgID是VB.CommandButton. Name是控件的名称. Container是包含添加控件的容器,可以为form或Frame控件等等。 Option Explicit '通过使用WithEvents关键字声明一个对象变量为新的命令按钮 Private WithEvents NewButton As CommandButton '增加控件 Private Sub Command1_Click() If NewButton Is Nothing Then '增加新的按钮cmdNew Set NewButton = Controls.Add("VB.CommandButton", "cmdNew", Me) '确定新增按钮cmdNew的位置 NewButton.Move Command1.Left + Command1.Width + 240, Command1.Top NewButton.Caption = "新增的按钮" NewButton.Visible = True End If End Sub '新增控件的单击事件Private Sub NewButton_Click() MsgBox "您选中的是动态增加的按钮!"End Sub
删除控件使用Remove方法,但只能删除那些用Add方法添加的控件.对于上面添加的控件NewButton,可以用如下代码删除.Private Sub Command2_Click()If NewButton Is Nothing ThenElseControls.Remove NewButtonSet NewButton = NothingEnd IfEnd Sub
http://www.zdnet.com.cn/developer/code/story/0,2000081534,39066261,00.htm
Add方法在Controls集合中添加一个控件并返回一个对控件的引用。Add方法的语法为:Object.Add(ProgID,Name,Container)其中Object为要添加元素的集合,ProgID为标示的字符串.可通过对象浏览器来确定,例如,CommandButton控件的ProgID是VB.CommandButton. Name是控件的名称. Container是包含添加控件的容器,可以为form或Frame控件等等。 Option Explicit '通过使用WithEvents关键字声明一个对象变量为新的命令按钮 Private WithEvents NewButton As CommandButton '增加控件 Private Sub Command1_Click() If NewButton Is Nothing Then '增加新的按钮cmdNew Set NewButton = Controls.Add("VB.CommandButton", "cmdNew", Me) '确定新增按钮cmdNew的位置 NewButton.Move Command1.Left + Command1.Width + 240, Command1.Top NewButton.Caption = "新增的按钮" NewButton.Visible = True End If End Sub '新增控件的单击事件Private Sub NewButton_Click() MsgBox "您选中的是动态增加的按钮!"End Sub
UnLoad 控件 '删除