Application Events

As a footnote to the Custom Events postings, the idea of a wrapper class is also how to handle Application events. The techniques are described on various MSDN pages, but here’s a summary.

Since a VBA project does not by default have a module that can hold handlers for Application events, you need to create a Class module, say AppWrapper. This has a WithEvents reference to the Application, plus whatever handlers are required:

Public WithEvents app As Word.Application

Private Sub App_WindowSelectionChange( _
                                  ByVal Sel As Selection)

This is in a Word template, and allows us to handle any change to the selected text (this was somewhat experimental, so I won’t explain why I wanted to do this).

Now we need to initialize the app reference, probably pretty soon after start-up. This is in the ThisDocument module:

Dim appwrap as New AppWrapper

Private Sub Document_New()
    Set = Word.Application

It’s a bit quirky syntactically that in the Class, “Word.Application” is a type, but in the initialization it’s an object reference.

This feels like a bit of a work-around, somehow. Why couldn’t each VBA project have an Application module, analogous to the ThisDocument/ThisWorkbook module, into which application-event handlers go? Admittedly, the contents of such modules would have to be combined, for all open projects, which could lead to name-clashes. But then there’s always one Active project, which could take precedence. Probably one of those things that’s not worth worrying about overmuch.


0 Responses to “Application Events”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

June 2009
« May   Jul »

%d bloggers like this: