Excel to Word - GetObject usage

S

Stan Mulder

What is wronge with this code intended to copy from an Excel worksheet to a
closed word document (with a formatted header)?
Thanks in advance !

Dim objWord As Object

On Error GoTo failed
'1st call without 1st argument returns reference to an instance of the _
application, and causes error(429) if .doc is not open.
Set objWord = GetObject("F:\LSD_050206\calcsht.doc")

failed:
If Err.Number = 429 Then
'2nd call specifies a file to open, starts it, returns ref. to existing
_
document & makes doc. visible
Set objWord = GetObject("F:\LSD_050206\calcsht.doc", Word.Application)
End If

Worksheets("Beam").Activate
With ActiveSheet
Worksheets("Beam").Range("A1: T55").Copy
End With

'release the reference
Set objWord = Nothing
 
J

Jezebel

Apart from the cludgy way of getting a reference to the Word document, the
big problem is that while you copy the excel stuff, you don't do anything
with it. You need to paste it into your document.

Dim objWord as object
Dim pDoc as object
Dim pDoc2 as object
Dim pOpenedHere as boolean
Const pFileName as string = "F:\LSD_050206\calcsht.doc"

'Get existing instance of Word if any; create new instance if necessary
on error resume next
set objWord = GetObject("Word.Application")
on error goto 0
if objWord is nothing then
set objWord = CreateObject("Word.Application")
pOpenedHere = true
end if

'Check if document is open already
for each pDoc in objWord.Documents
if pDoc.FullName = pFileName then
set pDoc2 = pDoc
exit for
end if
Next

'Open it if not
if pDoc2 is nothing then
set pDoc2 = objWord.Documents.Open(pFileName)
end if

'Copy the range
Worksheets("Beam.").Range("A1: T55").Copy

'Paste it (modify this to select the spot where you want to paste)
pDoc2.Range(pDoc2.End - 1, pDoc2.End).Paste

'Clean up
pDoc2.Save
pDoc2.Close
Set pDoc2 = Nothing

if pOpenedHere then
objWord.Quit
end if
set objWord = nothing
 

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