ControlCollection.AddControl 方法 (Control, Range, String)

将指定的 Control 添加到 ControlCollection 中的指定范围。

命名空间:  Microsoft.Office.Tools.Excel
程序集:  Microsoft.Office.Tools.Excel(在 Microsoft.Office.Tools.Excel.dll 中)

语法

声明
Function AddControl ( _
    control As Control, _
    range As Range, _
    name As String _
) As ControlSite
ControlSite AddControl(
    Control control,
    Range range,
    string name
)

参数

返回值

类型:Microsoft.Office.Tools.Excel.ControlSite
一个表示控件的对象,它包含工作表中的指定控件。

异常

异常 条件
ArgumentNullException

控件参数、名称参数或范围参数为 nullnull 引用(在 Visual Basic 中为 Nothing),或者名称参数长度为零。

ControlNameAlreadyExistsException

ControlCollection 实例中已存在一个同名控件。

InvalidRangeException

指定的范围无效。 不能使用多区域范围。 该范围应与 ControlCollection 实例同在一个工作表中。

备注

此方法可用于在运行时向 ControlCollection 添加任何控件。 有关更多信息,请参见 在运行时向 Office 文档添加控件

示例

下面的代码示例使用 AddControl 方法将两个自定义用户控件添加到工作表。 第一个控件添加到一组单元格。 第二个控件被添加到特定的位置。 代码更改第一个自定义用户控件的 Top 属性,此属性仅相对于工作表上包含该控件的 ControlSite 移动该控件。 然后,此代码设置由第二个用户控件返回的 ControlSite 对象的 Top 属性,以说明设置该控件的 Top 属性的正确方法。

    Private Sub ExcelRangeAddControl()

        Dim CustomUserControl As New UserControl1()
        Dim CustomUserControl2 As New UserControl2()

        Dim DynamicControl As Microsoft.Office.Tools.Excel.ListObject = Me.Controls.AddControl( _
            CustomUserControl, 0, 0, 150, 150, _
            "DynamicControl")

        Dim DynamicControl2 As Microsoft.Office.Tools.Excel. _
            ControlSite = 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.ControlSite dynamicControl =
        this.Controls.AddControl(customUserControl,
        0, 0, 150, 150, "dynamicControl");

    Microsoft.Office.Tools.Excel.ControlSite dynamicControl2 =
        this.Controls.AddControl(customUserControl2, 200, 0,
        150, 150, "dynamicControl2");

    customUserControl.BackColor = Color.Blue;
    customUserControl2.BackColor = Color.Green;

    customUserControl.Top = 100;
    dynamicControl2.Top = 100;
}

.NET Framework 安全性

请参见

参考

ControlCollection 接口

AddControl 重载

Microsoft.Office.Tools.Excel 命名空间