-->

In VSTO Addin for Excel how to handle a button cli

2019-09-01 05:32发布

问题:

Currently I am developing an Excel 2010 Addin using VB.NET 2010 with VSTO.

The active worksheet has a button, its click event will be handled by its own VBA code.

Now I would like to handle the same button click event in Addin without affecting its original VBA function. Is it possible? And how can I achieve this?

The pre-requisite of this task is that nothing is allowed to be changed on the Excel Template (including its VBA code). That's why I am trying from the event handling by VB.NET.

The trigger point is that the button in the Excel template is clicked, then it will surely raise certain event, and such event will certainly be handled by VBA macro, but I would like to add another listener (event handler) in VB.Net to the same event, so I can do some additional task.

Is there anyone know how to add such event handler?

Thanks.

回答1:

Here was a similar question.

var cmdButton = (Excel.Shape)xlWorkSheet.Shapes.AddOLEObject("Forms.CommandButton.1", Type.Missing, false, false, Type.Missing, Type.Missing, Type.Missing, 60, 60, 60, 60);

cmdButton.Name = "btnClick";

//var cmdBtn = (Microsoft.Vbe.Interop.Forms.CommandButton)Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet((Excel.Worksheet)xlApp.ActiveSheet, null, "btnClick", new object[0], null, null, null);

var cmdBtn = (Microsoft.Vbe.Interop.Forms.CommandButton)Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet((Excel.Worksheet)xlApp.ActiveSheet, null, "btnClick", new object[0], null, null, null);
//
//some button formatting codes
//
cmdBtn.Click +=cmdBtn_Click;


void cmdBtn_Click()// Command button click event handler
{
  MessageBox.Show("Test");
}

In your case it is easier, you don't need to create a button, you can just use it's name.