本帖最后由 wpxxsyzx 于 2012-11-17 13:45 编辑
3、 窗体 VSTO里窗体是类,所以显示窗体前必须实例化窗体,有两个方法分别用于显示模态和非模态的窗体 显示模态窗体如下: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim myform As New Form1 myform.ShowDialog() End Sub
显示非模态窗体如下 Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim myform1 As New Form1 myform1.Show() End Sub 4、 运行时添加控件 和窗体一样,添加控件之前要先实例化 Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click Dim i As Int16 Dim myCmb As New Microsoft.Office.Tools.Excel.Controls.ComboBox Dim selection = Globals.ThisWorkbook.Application.Selection If TypeName(selection).ToString = "Range" Then If selection.count = 1 Then myCmb = Me.Controls.AddComboBox(selection.left, selection.top, selection.width, selection.height, "新增") With myCmb.Items For i = 1 To 6 .Add(i) Next End With End If End If End Sub 5、 方法重载 在VBA中我们通过给过程设置可选参数来让一个过程实现不同的功能,这在VSTO里依然可用,但是我们还可以利用方法重载:定义多个名字相同的过程,每个过程的参数类型或个数不完全相同,调用过程时输入不同的参数就会调用不同的过程,这就是方法重载,例如: 下面的三个过程名字相同但参数不同 Private Sub sum(ByVal a As Int16, ByVal b As Int16, ByVal c As Int16) Me.Range("a1").Value = a + b + c End Sub Private Sub sum(ByVal a As Int16, ByVal b As Int16) Me.Range("a1").Value = a + b End Sub Private Sub sum(ByVal a As Int16) Me.Range("a1").Value = a End Sub 下面三个按钮调用sum过程但输入不同的参数,得到不同的结果 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Call sum(1, 2, 3) End Sub Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Call sum(1, 2) End Sub Private Sub Button3_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click Call sum(1) End Sub
6、 控件数组 VB中有控件数组可以只写一段代码,让一组控件实现相同的功能。VBA没有控件数组,要实现上述功能只能写类模块,VSTO也没有控件数组,但我们可以使用如下的方法。 Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click, Button5.Click, Button6.Click RadioButton1.Enabled = False End Sub 注意Handles子句,上段代码可以实现单击Button4, Button5, Button6都可以实现RadioButton1按钮不可用,就是说在Handles子句后跟上要实现相同功能的过程名就可以实现控件数组的功能,不需为每个按钮写相同的代码 |