« Managing Part Libraries With Linked Blocks | Main | Ware Brothers Networked Irrigation Controller »

Automating Word, Add-In vs. Template

At its simplest, the problem is to run some code when CTRL-ALT-A is pressed while editing a Microsoft Word 2003 file.

The code that runs wants to be written in C# and it’s purpose is to modify the content and styles of the current document.

In my first solution, I created a Word Add-In (using Visual Studio Tools for Office) and Visual Studio 2003. The Add-In has to register its DLL under the right Office keys to be found by Word. When Word starts, the assembly’s Connect method gets called. It proceeds to install a new toolbar into Word containing a few buttons. It’s easy to connect the Click event of the buttons with the C# code I want to run. Getting the code to run in response to a CTRL-ALT-A is considerably harder.

The first trick was to discover that a macro of the form below will invoke the C# event handler assigned to a toolbar button:

Sub TonesNotesNew()

    Dim cb As CommandBar

    Set cb = Application.CommandBars("TonesNotes")

    Dim cbc As CommandBarButton

    Set cbc = cb.FindControl(Tag:="New")

    cbc.Execute

    cbc.State = msoButtonUp

End Sub

The last piece of plumbing is to assign CTRL-ALT-A to invoke the macro “TonesNotesNew”.

The second time around I implemented the same functionality as a Word template file which is one of the new Visual Studio 2005 beta 2 project templates. The template file now holds the macros, the styles I use for this functionality, and the C# assembly that does the actual work.

 

 

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)