Open Word Document and Bring to Front

You can achieve what you want using APIS. I am using two APIs SetForegroundWindow and FindWindow

Private Declare Function SetForegroundWindow 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

Sub Sample()
    Dim objWord As Object, docWord As Object
    Dim strPath As String, FileName As String
    Dim hwnd As Long

    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True

    '~~> Change this to the relevant Filename and path
    strPath = "C:\Users\Siddharth Rout\Desktop\Sample.docx"
    '~~> Put the acutal file name here without the extension
    FileName = "Sample"

    Set docWord = objWord.Documents.Open(FileName:=strPath, ReadOnly:=True)

    hwnd = FindWindow(vbNullString, FileName & " [Read-Only] - Microsoft Word")

    If hwnd > 0 Then
      SetForegroundWindow (hwnd)
    End If
End Sub

NOTE: If you are sure that there is no other Word Application open other than what you opened then you can use this as well :)

Private Declare Function SetForegroundWindow 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

Sub Sample()
    Dim objWord As Object, docWord As Object
    Dim strPath As String
    Dim hwnd As Long

    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True

    '~~> Change this to the relevant Filename and path
    strPath = "C:\Users\Siddharth Rout\Desktop\Sample.docx"

    Set docWord = objWord.Documents.Open(FileName:=strPath, ReadOnly:=True)

    hwnd = FindWindow("OpusApp", vbNullString)
    If hwnd > 0 Then
      SetForegroundWindow (hwnd)
    End If
End Sub

How about,

docWord.Activate

This should bring the file that has been "Set" for the docWord object to foreground.

EDIT: Tested this on Access, quiet unreliable on Excel. Using an API is the best way to go if there are multiple instances of the Word application running.


Once you've opened a document (or added one) you can get a Hwnd to pass to the SetForegroundWindow API function from the ActiveWindow object (e.g. obWord.ActivieWindow.Hwnd). That way you don't need to search for the correct Word instance to bring to front.

Tags:

Ms Word

Excel

Vba