用类的时候用new 控件应该不用new比如vb自带的控件 dim btnMy as commandbutton 而不用new
2.使用Controls集合的Add方法,例: Dim a As CommandButton Set a = Controls.Add("VB.CommandButton", "a2") 'a2是这个控件的名称,即name属性 a.Left = 0 a.Top = 0 a.Caption = "a2" a.Visible = True例2:Dim a As VScrollBar Set a = Controls.Add("VB.VScrollBar", "vsbar") a.Left = 7485 a.Top = 3945 a.Visible = True删除: Controls.Remove a Set a = Nothing*************************************************************** ************************************************************** 复杂的 ¥¥¥¥1.新建一个工程,窗体Form1为缺省窗体,Form1的属性项Caption=″动态增减控件的例子″。 2.加入两个命令按钮(CommandButton),其中: Command1的属性项Caption=″增加控件″; Command2的属性项Caption=″删除控件″。 3.加入如下代码,运行该工程,单击″增加控件″则出现新增按钮。若单击″新增按钮″时会出现对话框,表明你触发的是动态增加控件的单击事件。 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 Command2_Click() If NewButton Is Nothing Then Else Controls.Remove NewButton Set NewButton = Nothing End If End Sub ′新增控件的单击事件 Private Sub NewButton_Click() MsgBox ″您选中的是动态增加的按钮!″ End Sub 注意:如果你希望添加一个用户控件或任何 ActiveX 控件到您的窗体,必须把这个控件添加到“工具箱”,或者把控件的 License 关键字添加到 Licenses 集合中。而且,你不能选定“工程属性”对话框的“生成” 选项卡上的“删除有关未使用的 ActiveX 控件”选项,否则controls.Add 方法将失败,因为必需的信息已经被丢失。
CommonDialog也不能用New
控件应该不用new比如vb自带的控件
dim btnMy as commandbutton
而不用new
Dim a As CommandButton
Set a = Controls.Add("VB.CommandButton", "a2") 'a2是这个控件的名称,即name属性
a.Left = 0
a.Top = 0
a.Caption = "a2"
a.Visible = True例2:Dim a As VScrollBar
Set a = Controls.Add("VB.VScrollBar", "vsbar")
a.Left = 7485
a.Top = 3945
a.Visible = True删除: Controls.Remove a
Set a = Nothing***************************************************************
**************************************************************
复杂的
¥¥¥¥1.新建一个工程,窗体Form1为缺省窗体,Form1的属性项Caption=″动态增减控件的例子″。
2.加入两个命令按钮(CommandButton),其中:
Command1的属性项Caption=″增加控件″;
Command2的属性项Caption=″删除控件″。
3.加入如下代码,运行该工程,单击″增加控件″则出现新增按钮。若单击″新增按钮″时会出现对话框,表明你触发的是动态增加控件的单击事件。
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 Command2_Click()
If NewButton Is Nothing Then
Else
Controls.Remove NewButton
Set NewButton = Nothing
End If
End Sub
′新增控件的单击事件
Private Sub NewButton_Click()
MsgBox ″您选中的是动态增加的按钮!″
End Sub
注意:如果你希望添加一个用户控件或任何 ActiveX 控件到您的窗体,必须把这个控件添加到“工具箱”,或者把控件的 License 关键字添加到 Licenses 集合中。而且,你不能选定“工程属性”对话框的“生成” 选项卡上的“删除有关未使用的 ActiveX 控件”选项,否则controls.Add 方法将失败,因为必需的信息已经被丢失。