I've successfully implemented the Microsoft sample "Walkthrough: Synchronizing a Custom Task Pane with a Ribbon Button" found here: http://msdn.microsoft.com/en-us/library/bb608590.aspx
Initially I ran into a problem with the task pane not showing, which turned out to be the result of some conflict between my add-in and Microsoft's "Analysis Toolpack". Once I disabled Analysis Toolpack the custom task pane began to show and hide as expected.
I then wrote some code to alter cells in a selected range when the user presses a button. That seemed to work just fine -- until I opened another workbook! Each workbook window got its own add-in ribbon, but when I clicked the toggle button to open/close the custom task pane it would only open/close the custom task pane for the first window that was created. This is regardless of which window I click the toggle button in.
The code instantiates the CustomTaskPane object in ThisAddIn_Startup (just like in the example code). The only thing I've added really is the button action in the UserControl:
using xl = Microsoft.Office.Interop.Excel;
namespace SynchronizeTaskPaneAndRibbon
{
public partial class TaskPaneControl : UserControl
{
public TaskPaneControl()
{
InitializeComponent();
}
private void actionButton1_Click(object sender, EventArgs e)
{
xl.Range selection_rng = Globals.ThisAddIn.Application.Selection;
foreach (xl.Range cell in selection_rng.Cells)
{
if (cell.Value is string)
{
string v = cell.Value;
cell.Value = v + "*";
}
}
}
}
}
The rest of the code is just as it is in the example.
Is there a way to change the example so that it will work for open multiple workbooks? What I want is for the same Add-In to appear in each workbook window, with the same Ribbon and with the same Custom Pane. And, of course, to have any ribbon actions (such as a button press) route to the custom task pane that appears within the same window.
Yes there is another example on MSDN which talks about managing custom taskpanes in multiple documents. Do note that this is from the perspective of Word/InfoPath but the underlying idea will be same for Excel too.
Broadly speaking, you need to add a new taskpane for current workbook if it does not have one. So move the adding of custom taskpane logic from Addin startup to ribbon button click event. Doing this in button click event gives you opportunity to add a new taskpane to current document when ribbon is clicked.
Link: https://msdn.microsoft.com/en-us/library/bb264456(v=office.12).aspx?f=255&MSPPError=-2147217396#Anchor_2
Putting the useful code snippets below in case the link goes dead in future:
Instead of removing, I recommend hiding the taskpane by toggling Visible flag to false but YMMV. Hope this helps.