Bring Application to Front (1 Viewer)

JaedenRuiner

Registered User.
Local time
Today, 01:01
Joined
Jun 22, 2005
Messages
154
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

AWF VIP
Local time
Yesterday, 23:01
Joined
May 3, 2004
Messages
1,409
Here a little API is required. Paste the following code into the declarations section of a module in your database:
Code:
Public Declare Function SetForegroundWindow Lib "user32" ( _
    ByVal hWnd As Long) _
    As Long

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

To set the focus to a program-instantiated session of Excel:
Code:
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:
Code:
Public Declare Function FindWindowA Lib "user32" ( _
    ByVal lpClassName As String, _
    ByVal lpWindowName As String) _
    As Long

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

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

Users who are viewing this thread

Top Bottom