I have now helped about half a dozen customers over the last 3 years to perform this very same task. In each case the scenario is the same:
- They have documents that are very specific to their system
- They want to create an add-in to assist with the management of these documents.
- They only want the add-in to load when one of their document is opened.
- BONUS: They also want to remove other add-ins
- BONUS: They would like a pristine instance of Word or Excel.
There are several methods to accomplish each of these tasks. But the one I find is easiest to maintain is what I call the “Master Add-in” approach.
In the “Master Add-in” you essentially attach one event: DocumentOpen or WorkbookOpen. You place code in the event to detect whether it is a document you care about. This can be done in several ways:
- You can look at the path where the file came from.
- You can look at the name of the file, if there is a specific naming convention you follow.
- Or, you can tag he document with Document Properties or Custom Xml Parts.
Once you have identified that it is a document you care about you follow this basic process:
- Get the path to the file being open and store it.
- Close the workbook or document being passed into the Open event.
- Create a new Instance of Word or Excel.
- Iterate through the COM Add-ins collection and the Add-ins collection and disable everything you do not want running. This includes disabling the Master Add-in as you do not want it running for the next parts.
- Locate your COM Add-in in the collection and set Connect = true.
- Open the document or workbook from the application object.
You will now have two instances of Excel or Word open. One that the user was originally working with which has the Master Add-in loaded and then the new one that is customized with your specific add-in and only your add-in.
This is useful for when you have multiple versions of your system and you can update the Master to recognize which version to launch.
Getting this to work just right is sometimes a challenge and you have to be careful not to disable all the add-ins for all instances. I have a few customer examples that I have built and will work on cleaning them up. I will combine the best parts and will write a new entry in the future which will walk you through creating one.