Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current Workbook Object in C#

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.

like image 744
Adam H Avatar asked Oct 27 '11 13:10

Adam H


People also ask

How do I find my current workbook name?

VBA code: Get workbook name Press Alt + Q keys to close the Microsoft Visual Basic Application window and return to the workbook. 5. Select a blank cell, type =GetBook() into the cell, then press the Enter key. You can see the workbook name is populated on the selected cell.

What does ActiveWorkbook mean in VBA?

The ActiveWorkbook is the workbook that you (or the user) has selected before running the macro. The ActiveSheet is the worksheet tab that is currently selected before running the macro. If multiple sheets are selected, the ActiveSheet is the sheet that is currently being viewed.

What is current workbook in Excel?

CurrentWorkbook is the workbook you're in and using Power Query. Power Query lists in a dialog all the items in this current workbook that are in this workbook.


2 Answers

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;
like image 56
tuncalik Avatar answered Oct 18 '22 22:10

tuncalik


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

like image 38
Russell Saari Avatar answered Oct 18 '22 22:10

Russell Saari