Problem Opening Word 2007 from another Office Application

L

LA Lawyer

I am using the following code (from Access 2007) to open Word. This is
supposed to start Word if it is not already running, but fails unless Word
is running. What did I do wrong? Here is the full code (including some
stuff about saving the new document which has, I presume, nothing to do with
this issue):


Public Function StartWord(Optional OpenWith As String, Optional SaveItAs As
String)
Dim WordApp As Word.Application
Dim WordWasNotRunning As Boolean
Dim WordDoc As Word.Document

'Get existing instance of Word if it's open; otherwise create a new one

On Error Resume Next
Set WordApp = GetObject(, "Word.Application")
If Err Then
Set WordApp = New Word.Application
WordWasNotRunning = True
End If
Set WordDoc = WordApp.Documents.Add(OpenWith)
With WordApp
.Visible = True
.Activate
.WindowState = wdWindowStateMaximize
If Not IsNull(SaveItAs) Then
Dim OriginalSaveItAs As String
OriginalSaveItAs = SaveItAs
Dim theTempNum As Integer
theTempNum = 1

Do Until Len(SaveItAs) = 0 ', i.e., the file doesn't already exist
SaveItAs = InStr(1, OriginalSaveItAs, "." - 1) & "(" &
CStr(theTempNum) & ")" & Right(OriginalSaveItAs, 4)
theTempNum = theTempNum + 1
Loop
.ActiveDocument.SaveAs FileName:=SaveItAs
End If
End With
End Function
 
J

Jay Freedman

The code to create the Word instance looks correct, but that isn't the whole
story. To help in troubleshooting, please answer these questions:

- When it fails, _how_ does it fail? If there is an error message, _exactly_
what does it say?
- If you put a breakpoint at the Set WordApp line and single-step the code
with F8 from there, on what line does the code fail? What are the values of
the variables at that time?
- What is the value of the string OpenWith? (According to the syntax of the
Documents.Add method, it should be the name of a template on which to base
the new document, or an empty string to get a document based on
Normal.dotm.)

If the Word instance does start up, you may be having trouble with the
assignment of the name of the file to SaveItAs; I would expect a syntax
error in the InStr function as written. Instead of

InStr(1, OriginalSaveItAs, "." - 1)

I think you want

Left(InStr(1, OriginalSaveItAs, ".") - 1)

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top