如何以编程方式将复选框控件添加到Excel单元格或选中或取消选中现有复选框

问题描述:

我正在C#中使用Excel COM对象,并希望将一个复选框动态地插入到Excel工作表中,并根据条件对其进行选中或取消选中.

I am using the Excel COM object in C# and want to insert a checkbox dynamically to an Excel sheet and make it checked or unchecked based on a condition.

OR

如何以编程方式将Excel工作表中的现有复选框标记为已选中. 我环顾四周,但没有找到任何解决方案.

how can i mark as checked an existing checkbox in the Excel sheet programatically. I have looked around and I didn't find any solution.

您始终可以在MS Excel中记录一个宏,它可以使您很好地了解为了实现目标需要使用Excel对象做什么.例如,当为您的问题记录宏时,它带有以下代码:

You can always record a macro in MS Excel and it will give you a good idea of what needs to be done with Excel object in order to achieve something. For example, when recording macro for your problem, it came out with the following code:

ActiveSheet.OLEObjects.Add(ClassType:="Forms.CheckBox.1", Link:=False, _
        DisplayAsIcon:=False, Left:=65.25, Top:=24, Width:=108, Height:=21). _
        Select

我希望从这里您可以看到需要执行哪些操作才能在活动工作表上插入复选框.

I hope that from here you can see what needs to be done to insert checkbox on the active sheet.

以下是更详细的说明(Visual Studio 2010和C#): 1.启动Visual Studio并创建新项目(Windows应用程序或控制台应用程序) 2.右键单击引用",然后选择添加引用" 3.选择COM引用并添加Microsoft Excel xx.x对象库(在我的情况下xx.x是14.0,即Excel 2010). 4.在代码中的某个位置(某些功能(例如Main或单击某个按钮))添加以下代码:

Here is more detailed explanation (Visual Studio 2010 and C#): 1. Fire up Visual Studio and create new project (windows app or console app) 2. Right click on References and select "Add Reference" 3. Select COM references and add Microsoft Excel xx.x Object Library (in my case xx.x is 14.0 which is Excel 2010). 4. Somewhere in your code (some function like Main or some click on a button) add this code:

// Start excel
Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;

// Get a sheet 
Microsoft.Office.Interop.Excel._Workbook oWB = (Microsoft.Office.Interop.Excel._Workbook)oXL.Workbooks.Add(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel._Worksheet oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

// Get ole objects and add new one
Microsoft.Office.Interop.Excel.OLEObjects objs = oSheet.OLEObjects();

// Here is the method that is posted in the answer
Microsoft.Office.Interop.Excel.OLEObject obj = objs.Add("Forms.CheckBox.1", 
    System.Reflection.Missing.Value,
    System.Reflection.Missing.Value,
    false,
    false,
    System.Reflection.Missing.Value,
    System.Reflection.Missing.Value,
    65.25,
    24,
    108,
    21);
// Here, you are making it checked. obj.Object is dynamic, so you will not get help from visual studio, but you know what properties CheckBox can have, right?
obj.Object.Value = true;

我希望这会有所帮助.