Microsoft Office Tutorials and References
In Depth Information
Activating the Word Application
Activating the Word Application
The basic premise of activating Word is that you must tell Excel you are leaving it altogether, for
a totally different application destination. The GetObject function is a reliable way to do this, as
shown in the following macro:
Sub ActivateWord()
Dim wdApp As Object
Set wdApp = GetObject(, “Word.Application”)
wdApp.Activate
End Sub
The GetObject function has two arguments, the first of which is an optional pathname argument
that tells VBA where to look for a specified object. Because the pathname is not specified (which it
need not be because it is optional), GetObject activates Word, because Word.Application is the
object being specified in the second argument.
But what if Word is not open? If you try running the ActivateWord macro without Word being
open, a runtime error will occur because VBA is being told to activate an object that is not able to
be activated. You need to insert an error bypass in your macro to tell VBA to activate Word only if
Word is open, and to open and then activate Word only if Word is closed.
You can accomplish this with the On Error Resume Next statement that monitors runtime error
number 429, which is the VBA error number that occurs with the GetObject function if Word is
not open. In that case, VBA will open a new instance of Word, as shown in the following modified
ActivateWord macro:
Sub ActivateWord()
Dim wdApp As Object
On Error Resume Next
Set wdApp = GetObject(, “Word.Application”)
If Err.Number = 429 Then
Err.Clear
Set wdApp = CreateObject(“Word.Application”)
wdApp.Visible = True
End If
wdApp.Activate
End Sub
opening and Activating a Word document
Now that you have Word open, it’s reasonable to assume that the next item on your agenda is to
open an existing Word document, or to create a new Word document. If the plan is to open an
existing document, a wise programming practice is to account for the possibility that the document does
not exist in the specified folder path.
You never know — files get deleted, or have their names changed, or get moved
from one folder to another. A VBA runtime error will eventually come back to
bite you when a command is given to open a file having an unrecognized name
or location.
 
Search JabSto ::




Custom Search