Group:  Microsoft Word ยป microsoft.public.word.oleinterop
Thread: Opening Word from Excel with Macro.

Geek News

Opening Word from Excel with Macro.
JuanK 3/15/2007 9:14:20 PM
Hello,

I'm writing a Macro in Excel that opens a Word document.
This is the code:

Sub Macro1()

Dim WordDoc As Object

Set WordDoc = CreateObject("Word.Application")
WordDoc.Documents.Open "C:\Wordfile.doc"
WordDoc.Visible = True

' CODE

WordDoc.Documents("C:\Wordfile.doc").Close SaveChanges:=wdDoNotSaveChanges
WordDoc.Quit
Set WordDoc = Nothing

End Sub

This code works fine as long as there were any Word document previously
opened.

But, if there is a word document previously opened, when "Wordfile.doc"
closes, an error dialog appears: "This file is in use by another application
or user, (C:\Documents and Settings\...\Normal.dot)". And then a "Save As"
dialog opens to save this Normal.dot.

What should I do to avoid this? I would appreciate it if you can help me
with this.

Thank you so much.

JuanK
Re: Opening Word from Excel with Macro.
Cindy M. <C.Meister-C[ at ]hispeed.ch> 4/19/2007 5:20:17 PM
Hi =?Utf-8?B?SnVhbks=?=,

[Quoted Text]
> I'm writing a Macro in Excel that opens a Word document.
> This is the code:
>
> Sub Macro1()
>
> Dim WordDoc As Object
>
> Set WordDoc = CreateObject("Word.Application")
> WordDoc.Documents.Open "C:\Wordfile.doc"
> WordDoc.Visible = True
>
> ' CODE
>
> WordDoc.Documents("C:\Wordfile.doc").Close SaveChanges:=wdDoNotSaveChanges
> WordDoc.Quit
> Set WordDoc = Nothing
>
> End Sub
>
> This code works fine as long as there were any Word document previously
> opened.
>
> But, if there is a word document previously opened, when "Wordfile.doc"
> closes, an error dialog appears: "This file is in use by another application
> or user, (C:\Documents and Settings\...\Normal.dot)". And then a "Save As"
> dialog opens to save this Normal.dot.
>
> What should I do to avoid this? I would appreciate it if you can help me
> with this.
>
I assume you'd want to leave the application running, if it's already been
started by the user. Take a look at the GetObject method. You can use this to
find out if Word is already running and set a module-level (global) boolean
variable to hold the information.

(If Word is not running, GetObject will return Error 429, which you can trap or
ignore using basic error handling techniques.)

At the end, check the variable's value and only use wordDoc.Quit if it's false.

Cindy Meister
INTER-Solutions, Switzerland
http://homepage.swissonline.ch/cindymeister (last update Jun 17 2005)
http://www.word.mvps.org

This reply is posted in the Newsgroup; please post any follow question or reply
in the newsgroup and not by e-mail :-)

Home | Search | Terms | Imprint Contact
Newsgroups Reader - provided by WiredBox.Net