Activating Excel From Another Application
This page describes how to activate the Excel application when you are controlling it via Automation from another application.
If you are doing cross-application programming, such as
working in Word with code to automate Excel, you may find it useful for the
user's convenience to activate the main Excel window from code running in Word
while Word is the active application. You can try to use the AppActivate
statement, but this requires that you know in advance the caption of the window
you want to activate. Moreover, I have found AppActivate to be somewhat flakey. Sometimes
it works and sometime not (raising an error 5, Invalid Procedure Call).
Moreover it does not always set keyboard focus to the application.
You can work around these problems with AppActivate with a
few simple Windows API functions. The following code will activate the
main Excel window and set keyboard focus to the ActiveSheet in Excel.
Paste the following code into a new code module, and run the macro ActivateExcel.
Note that you must not have any VBA Editors open. If you have a
VBA Editor open, the system will set focus to that Editor window, rather than to
Excel. This problem has largely been fixed in Excel 2007.
For a list of application window classes for most Office applications (versions
2003 and 2007 only) click here.
You can download an
bas module file here
containing the code below.
This code should work for any Office application whose
window class is known. Change the value of C_MAIN_WINDOW_CLASS from XLMAIN to
the window class of the other application (e.g., OpusApp for Word)

Option Explicit
Option Compare Text
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' modActivateExcel
' By Chip Pearson, www.cpearson.com, chip@cpearson.com
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Window API Declarations
' These Declares MUST appear at the top of the
' code module, above and before any VBA procedures.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Declare Function BringWindowToTop Lib "user32" ( _
ByVal HWnd As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" ( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) As Long
Private Declare Function SetFocus Lib "user32" ( _
ByVal HWnd As Long) As Long
Public Sub ActivateExcel()
Dim Res As Long
Dim XLHWnd As Long
Const C_MAIN_WINDOW_CLASS = "XLMAIN"
XLHWnd = FindWindow(lpClassName:=C_MAIN_WINDOW_CLASS, _
lpWindowName:=vbNullString)
If XLHWnd > 0 Then
Res = BringWindowToTop(HWnd:=XLHWnd)
If Res = 0 Then
Debug.Print "Error With BringWindowToTop: " & _
CStr(Err.LastDllError)
Else
SetFocus HWnd:=XLHWnd
End If
Else
Debug.Print "Can't find Excel"
End If
End Sub
This page last modified: 2-July-2007.