Get the current Workbook Object in C#

[亡魂溺海] 提交于 2019-11-27 02:48:04

问题


I've been writing an application in C# which creates Custom Document properties in an Excel spreadsheet, I have a function for this which takes in a Workbook Object...

However, actually getting the current Workbook object is proving to be quite annoying, I am using ExcelDNA to add functionality, however, I can't seem to pass my function a valid Workbook COM object.


回答1:


This is the way I am currently doing it it seems to work really well

 using Excel = Microsoft.Office.Interop.Excel;      

Then you get 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 would try what you have and see how it works

Hope this helps




回答2:


If you need to find the activeworkbook with C#, if you are using Office Interop, you can try this kind of code:

(Workbook)Globals.ThisAddIn.Application.ActiveWorkbook;

[Source]




回答3:


As @Govert explained above 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;



回答4:


GetActiveObject() looks in the Running Object Table (ROT) and gives you the last Excel instance opened which may not corresponding with top Z order excel window.

Loop through the Z order and find the matching workbook.

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



来源:https://stackoverflow.com/questions/7916711/get-the-current-workbook-object-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!