View Full Version : Bring Application to Front


JaedenRuiner
07-18-2007, 07:05 AM
So, through VBA I am automating multiple office applications, but occasionally, other applications like Explorer, or notepad get in the front of one of my automated applications. It would nice, if on my user form I could have a button that would bring Excel or Word back to the foreground of the windows desktop.

I have tried the Activate method, but that seems to only select the workbook/worksheet for use, it doesn't bring it to the front as if the user had pressed ALT+Tab. I want to internally "switch" to the other application via code. Is that possible?

Thanks
Jaeden "Sifo Dyas" al'Raec Ruiner

ByteMyzer
07-18-2007, 07:56 AM
Here a little API is required. Paste the following code into the declarations section of a module in your database:
Public Declare Function SetForegroundWindow Lib "user32" ( _
ByVal hWnd As Long) _
As Long

For example, to set the focus to your instance of Access:
SetForegroundWindow Application.hWndAccessApp

To set the focus to a program-instantiated session of Excel:
Dim objXL As Object

Set objXL = CreateObject("Excel.Application")
objXL.Visible = True
.
.
.
SetForegroundWindow objXL.Hwnd

Word, however, does not offer the Hwnd object in its Application class. An additional declaration is needed:
Public Declare Function FindWindowA Lib "user32" ( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) _
As Long

To use these two API calls for Word:
Dim objWord As Object, hWnd As Long, cap As String

Set objWord = CreateObject("Word.Application")
objWord.Visible = True
' Temporarily change the Word caption to something unique,
' find the window by its unique caption, capture the hWnd,
' then restore the caption
cap = objWord.Caption
objWord.Caption = "-MyUniqueCaption-"
hWnd = FindWindowA(vbNullString, "-MyUniqueCaption-")
objWord.Caption = cap
.
.
.
SetForegroundWindow hWnd