Get the application window handle in any app (well ... in Excel, Word, Access, PowerPoint or Outlook)
- John
- 3 days ago
- 2 min read
Updated: 2 days ago
To me, this is 'any app' because I only develop VBA code for Excel, Word, Access, PowerPoint and Outlook. I appreciate VBA can be used in other host applications ... but I don't support those applications.
I wanted to have a simple piece of code that I could drop into any host application in which I am developing VBA code that would get me the application window handle. Getting this is straight-forward in Excel, Word and Access ... while different code is required for each of these applications (and so in the code, below, it purposefully uses the Application object 'late bound' in order to avoid compilation errors), the Application object provides a property (or, in the case of Word, the Application object provides a property which provides a property which provides a property!) which gives us the handle.
However, in PowerPoint and Outlook this is not so straight-forward as the Application object does not provide such a property and so the Windows API function FindWindow is used.
Add a new standard Module in your VBA Project and add this code:
This uses the 'Unicode' variant of the FindWindow function (i.e. FindWindowW where the trailing W standards for "wide" meaning Unicode ... as opposed to FindWindowA where the trailing A stands for ANSI). As such, to avoid VBA's built-in behaviour of converting all Strings from (it's native) Unicode to ANSI when passing them into Windows API functions, the code passes-in pointers to the Strings using the StrPtr function AND the types of the relevant parameters of the Windows API function are converted from String to Long/Ptr.
Why do this? The edge case that is being catered for here is a PowerPoint presentation being saved with a Unicode character in its file name. That is definitely an edge case!
A usage example is, then:
To read more about the FindWindow function, see https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-findwindoww. I would also include a link to the official Microsoft documentation for StrPtr ... but there isn't any such documentation!
コメント