How to do something when create a new workbook?  
Author Message
Xinwen





PostPosted: Visual Studio Tools for Office, How to do something when create a new workbook? Top

Hi Super Men,

I wanna know how can I do something when I click the "New" button of Excel to create a new workbook

I try to use "this.New += new Microsoft.Office.Tools.Excel.WorkbookEvents_NewEventHandler(ThisWorkbook_New);" in "ThisWorkbook.cs", and write something in "void ThisWorkbook_New()" method, but when I click the "New" button, it doesn't run this code!!!




Visual Studio Tools for Office18  
 
 
Xinwen





PostPosted: Visual Studio Tools for Office, How to do something when create a new workbook? Top

Actually, I try it in this way:

//////////////////////////////////////

Excel.Workbook workbook = new Excel.Workbook();

((Excel.AppEvents_Event)workbook).NewWorkbook += new Excel.AppEvents_NewWorkbookEventHandler(workbook_NewWorkbook);

void workbook_NewWorkbook(Excel.Workbook wb)
{
      ......
}

//////////////////////////////////////

It still can't work correct !!!



 
 
Cindy Meister





PostPosted: Visual Studio Tools for Office, How to do something when create a new workbook? Top

Hi Xinwen

Let me make sure I understand correctly. This is a VSTO solution, and you want to capture when the user creates a new workbook

The NewWorkbook event is an application level event. Since there's also a property of the same name, Intellisense won't show this to you unless you explicitly cast the application object to the application events:

            ((Excel.AppEvents_Event)ThisApplication).NewWorkbook += new Microsoft.Office.Interop.Excel.AppEvents_NewWorkbookEventHandler(ThisWorkbook_NewWorkbook);

The event handler:

        void ThisWorkbook_NewWorkbook(Microsoft.Office.Interop.Excel.Workbook Wb)
        {
            MessageBox.Show("New workbook" + Wb.Name);
        }

The procedure you were trying to work with is only valid in the ThisWorkbook VBA project. It can't be used outside the immediate Excel environment.



 
 
ZeroCool127





PostPosted: Visual Studio Tools for Office, How to do something when create a new workbook? Top

Hi Cindy,

Thank you so much, and I'll try this way latter. You gave me very good idea, thanks!!!



 
 
markand





PostPosted: Visual Studio Tools for Office, How to do something when create a new workbook? Top

Hi

Is there a way to use the Microsoft.Office.Interop.Excel.AppEvents_NewWorkbookEventHandler mentioned in the above example to be called even before the New Workbook functionality takes place.

Markand