gpt4 book ai didi

c# - 从 Excel 文档中的代码隐藏访问 ActiveX 或表单对象(文本框)

转载 作者:太空狗 更新时间:2023-10-29 17:53:18 26 4
gpt4 key购买 nike

Excel 文件中有几个文本框作为 ActiveX 对象,我想从代码隐藏中访问它们。

我在其他领域使用 ClosedXML,但我愿意接受其他建议。

最佳答案

要从 C# 访问 OLE 对象,请添加对 Microsoft Forms 2.0 对象库的引用。您可以遍历所需复选框和文本框的控件。享受吧!

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;
}

关于c# - 从 Excel 文档中的代码隐藏访问 ActiveX 或表单对象(文本框),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39351011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com