There are several textboxes in an excel file as ActiveX objects and I want to reach them from codebehind.
I am using ClosedXML for other fields, but I am open for other suggestions.
Add an ActiveX control On the Developer tab, in the Controls group, click Insert, and then under ActiveX Controls, select a control, or click More Controls to view all the available ActiveX controls, and then select a control. Click the worksheet location where you want the ActiveX control to appear.
As Hans Passant said, Form controls are built in to Excel whereas ActiveX controls are loaded separately. Generally you'll use Forms controls, they're simpler. ActiveX controls allow for more flexible design and should be used when the job just can't be done with a basic Forms control.
For accessing OLE objects from C#, add reference to Microsoft Forms 2.0 object library. You can iterate through the controls for your desired checkbox and textbox. Enjoy !
using Excel = Microsoft.Office.Interop.Excel;
using VBE = Microsoft.Vbe.Interop.Forms;
private static void ExcelOperation(string xlFileName)
{
var xlApp = new Excel.Application();
var xlWorkbook = xlApp.Workbooks.Open(xlFileName);
var xlSheet = xlWorkbook.Worksheets["your_sheet_Name"] as Excel.Worksheet;
try
{
Excel.OLEObjects oleObjects = xlSheet.OLEObjects() as Excel.OLEObjects;
foreach (Excel.OLEObject item in oleObjects)
{
if (item.progID == "Forms.TextBox.1")
{
VBE.TextBox xlTB = item.Object as VBE.TextBox;
Console.WriteLine("Name: " + item.Name);
Console.WriteLine("Text: " + xlTB.Text);
Console.WriteLine("Value: " + xlTB.get_Value());
Marshal.ReleaseComObject(xlTB); xlTB = null;
}
else if (item.progID == "Forms.CheckBox.1")
{
VBE.CheckBox xlCB = item.Object as VBE.CheckBox;
Console.WriteLine("checkbox: " + item.Name);
Console.WriteLine("Value: " + xlCB.get_Value());
Marshal.ReleaseComObject(xlCB); xlCB = null;
}
}
Marshal.ReleaseComObject(oleObjects); oleObjects = null;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
Marshal.ReleaseComObject(xlSheet); xlSheet = null;
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook); xlWorkbook = null;
Marshal.ReleaseComObject(xlApp); xlApp = null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With