Access: Bringing the Word window to the front from code

Q: Susan H. writes that she has some standard code that creates a Word document and puts some Access data into it, using VBA Automation code. But sometimes the Word window is hidden behind other windows, either the Access window itself or some other window.

A: This is a long-standing problem in Office Automation. Many solutions have been proposed, some involving API calls or methods in obscure object models, but I have found that this procedure will do the job, supposing that you are using early binding and have set a reference to the Word object model:

Public Sub BringDocToFront(appWord As Word.Application, _

doc As Word.Document)

On Error GoTo ErrorHandler

With appWord

.Visible = True

.Activate

.ActiveWindow.WindowState = wdWindowStateNormal

doc.Select

doc.Activate

.Selection.HomeKey Unit:=wdStory

End With

 

ErrorHandlerExit:

Exit Sub

ErrorHandler:

MsgBox “Error No: ” & Err.Number _

& ” in BringDocToFront procedure; ” _

& “Description: ” & Err.Description

Resume ErrorHandlerExit

End Sub

You can of course use wdWindowStateMaximize if you want the Word window to be maximized.

Just call the procedure as needed from any procedure that creates a Word document you want to be visible at the end of the procedure, feeding it the Word Application variable and the Word Document variable as arguments:

Call BringDocToFront(appWord, doc)

Want More?

Office Watch has the latest news and tips about Microsoft Office.  Delivered once a week.