问题描述:

I have a C# Program which reads AND writes data from and to the same Excel File using Microsoft Interop (and afterwards do stuff with the data, e.g. exporting it to another interface).

So basically I have a class 'ExcelFileReader' in my Project, which opens the ExcelFile, read and write data, and close the file afterwards.

Code Snippet:

m_ExcelApp = new Excel.Application();

m_ExcelWorkBook = m_ExcelApp.Workbooks.Open(m_ExcelPath, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

As you can see, the third argument from the .open Method is false, which means 'readonly=false' (because as I already mentioned, I need to write data to the file). Hence, when I run my program, the Excel-File has to be closed.

What I want to do now, is writing an VBA Macro (included in my Excel-File), that starts my programm (and of course also read and write data to my now open Excel File). I know how to include the *.tlb file in Excel.

But what (I think) I need to do is something like passing a reference from the open Excel-File to my Application?!?

Do you have any ideas if this is possible and if so how I can do that? Thank you very much!

网友答案:

Got it! And it's not complicated!

In VBA it's possible to pass for example the reference for the workbook as a parameter in a method. So what I basically did, is passing the reference of the workbook to my TypeLibrary. And in my C#-Program I did not open my ExcelFile anymore but simply wrote

m_ExcelWorkBook = parameter_WorkBook;

That's it.

So yes. It is possible to pass an Excel-Workbook-Reference to a Type Library and work with it!

相关阅读:
Top