ControlCollection.AddControl 方法 (Control, Range, String) (2007 system)
更新:2007 年 11 月
将指定的 Control 添加到 ControlCollection 中的指定范围。
命名空间: Microsoft.Office.Tools.Excel
程序集: Microsoft.Office.Tools.Excel.v9.0(在 Microsoft.Office.Tools.Excel.v9.0.dll 中)
语法
声明
Public Function AddControl ( _
control As Control, _
range As Range, _
name As String _
) As OLEObject
用法
Dim instance As ControlCollection
Dim control As Control
Dim range As Range
Dim name As String
Dim returnValue As OLEObject
returnValue = instance.AddControl(control, _
range, name)
public OLEObject AddControl(
Control control,
Range range,
string name
)
参数
control
类型:System.Windows.Forms.Control要添加到 ControlCollection 实例的控件。
range
类型:Microsoft.Office.Interop.Excel.Range提供控件的边界的 Range。
name
类型:System.String可用于索引 ControlCollection 实例中控件的控件名称。
返回值
类型:Microsoft.Office.Tools.Excel.OLEObject
一个 OLEObject 实例,表示为该控件创建的容器。
异常
异常 | 条件 |
---|---|
ArgumentNullException | 控件参数、名称参数或范围参数为 nullnull 引用(在 Visual Basic 中为 Nothing),或者名称参数长度为零。 |
ControlNameAlreadyExistsException | ControlCollection 实例中已存在一个同名控件。 |
InvalidRangeException | 指定的范围无效。不能使用多区域范围。该范围应与 ControlCollection 实例同在一个工作表中。 |
备注
此方法可用于在运行时向 ControlCollection 添加任何控件。有关更多信息,请参见在运行时向 Office 文档添加控件。
示例
下面的代码示例使用 AddControl 方法将两个自定义用户控件添加到工作表。第一个控件添加到一组单元格。第二个控件被添加到特定的位置。代码更改第一个自定义用户控件的 Top 属性,此属性仅相对于工作表上包含该控件的 OLEObject 移动该控件。然后,此代码设置由第二个用户控件返回的 OLEObject 的 Top 属性,以说明设置该控件的 Top 属性的正确方法。
Private Sub ExcelRangeAddControl()
Dim CustomUserControl As New UserControl1()
Dim CustomUserControl2 As New UserControl2()
Dim DynamicControl As Microsoft.Office.Tools.Excel. _
OLEObject = Me.Controls.AddControl( _
customUserControl, 0, 0, 150, 150, _
"DynamicControl")
Dim DynamicControl2 As Microsoft.Office.Tools.Excel. _
OLEObject = Me.Controls.AddControl( _
customUserControl2, 200, 0, 150, 150, _
"DynamicControl2")
CustomUserControl.BackColor = Color.Blue
CustomUserControl2.BackColor = Color.Green
CustomUserControl.Top = 100
DynamicControl2.Top = 100
End Sub
private void ExcelRangeAddControl()
{
UserControl1 customUserControl = new UserControl1();
UserControl2 customUserControl2 = new UserControl2();
Microsoft.Office.Tools.Excel.OLEObject dynamicControl =
this.Controls.AddControl(customUserControl,
0, 0, 150, 150, "dynamicControl");
Microsoft.Office.Tools.Excel.OLEObject dynamicControl2 =
this.Controls.AddControl(customUserControl2, 200, 0,
150, 150, "dynamicControl2");
customUserControl.BackColor = Color.Blue;
customUserControl2.BackColor = Color.Green;
customUserControl.Top = 100;
dynamicControl2.Top = 100;
}
权限
- 对直接调用方的完全信任。此成员不能由部分信任的代码使用。有关更多信息,请参见通过部分受信任的代码使用库。