在Excel文档中从代码隐藏到达ActiveX或表单对象(文本框)

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

我在其他领域使用ClosedXML,但我打开其他build议。

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

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

您可以在VBA中创build文件(在%appdata%文件夹中),并在该文件中保存文本框的值( 例如,.ini文件 )。

之后,在C#中打开文件。

VBA(.xlsm文件)

 ' PtrSafe for 64bit (for 32bit, remove it) Private Declare PtrSafe Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" _ (ByVal lpApplicationName As String, ByVal lpKeyName As Any, _ ByVal lpString As Any, ByVal lpFileName As String) As Long Private Sub TextBox1_Change() WritePrivateProfileString "Page1", "TextBox1", TextBox1.Text, "C:\Users\HS\Desktop\exceltab.ini" End Sub 

C:\用户\ HS \桌面\ exceltab.ini

 [Page1] TextBox1=ok 

在这里输入图像说明

如果你使用的是ClosedXML,你应该看看XLWSContentManager

根据微软 :

ActiveX控件由OLEObjects集合中的OLEObject对象表示(所有OLEObject对象也都在Shapes集合中)

因此,使用ClosedXML,您需要使用XLWSContents.OleObjects ,但如果控件不是ActiveX控件,而是内置的Excel 表单控件,则需要使用XLWSContents.Controls

但是请注意MS文档 – ClosedXML的实现可能需要您检查形状。

您可以迭代所有的OLE对象如下所示,并通过文本框名称或文本框文本标识您需要的文本框。 而不是我,您可以使用工作簿外的工作表引用或任何代码。

 Private Sub GetActiveXControls() For Each Item In Me.OLEObjects 'Debug.Print Item.Name If TypeName(Item.Object) = "TextBox" Then Debug.Print "text = " & Item.Object.text End If Next End Sub 

如果你想使用ClosedXML,你可以链接textarea&cell与LinkedCell属性。

喜欢这个 :

在这里输入图像描述

参见:

在这里输入图像说明