Get current workbook object in C #

I am writing a C # application that creates Custom Document properties in an Excel spreadsheet, I have a function for that that takes a Workbook object ...

However, actually getting the current Workbook object is quite annoying, I use ExcelDNA to add functionality, but I can not pass my function to a real Workbook COM object.

+6
source share
4 answers

This is how I do it now, it seems that it works very well

using Excel = Microsoft.Office.Interop.Excel; 

Then you get an active workbook

  //Gets Excel and gets Activeworkbook and worksheet Excel.Application oXL; Excel.Workbook oWB; Excel.Worksheet oSheet; oXL = (Excel.Application)Marshal.GetActiveObject("Excel.Application"); oXL.Visible = true; oWB = (Excel.Workbook)oXL.ActiveWorkbook; docProps = oWB.CustomDocumentProperties 

Then I will try what you have and see how it works.

Hope this helps

+14
source

If you need to find a reference book with the C# function, if you use Office Interop, you can try this type of code:

 (Workbook)Globals.ThisAddIn.Application.ActiveWorkbook; 

[ Source ]

+15
source

As @Govert explained in his comment:

 using Excel = Microsoft.Office.Interop.Excel; using ExcelDna.Integration; // Get the correct application instance Excel.Application xlapp = (Excel.Application)ExcelDnaUtil.Application; // Get active workbook Excel.Workbook wbook = xlapp.ActiveWorkbook; 
+7
source

GetActiveObject () scans the Running Object (ROT) table and gives you the last Excel instance, which might not match the top Excel window.

Scroll through the Z-order and find the corresponding book.

See this link: - https://social.msdn.microsoft.com/Forums/office/en-US/060000d8-a899-49bf-a965-0576dee958d4/how-to-get-active-application?forum=exceldev

-1
source

Source: https://habr.com/ru/post/900203/


All Articles