Jim said:
I got it to work, but if I try it a second time I get this error:
The remote server machine does not exist or is unavailable.
The user will potentially be doing this several times in a session,
so having it only work the first time does me no good. Here's the
code I have:
Dim myRange As Range
Dim myDoc As Word.Document
Dim objWord As Word.Application
Set objWord = New Word.Application
Set myDoc = objWord.Documents.Add(docName, , , False)
Set myRange = myDoc.Range
myRange.Select
Selection.InsertAfter newText
objWord.ActiveDocument.SaveAs docName
objWord.ActiveDocument.Close
objWord.Quit
Set objWord = Nothing
'docName' is a variable with the fully qualified document name and
'newText' is a variable that will have the text I want to insert. I
also need to have a blank line inserted before my new line of text
is inserted. Right now it's just appending it to the end of the last
line of the document. I want to go to the end of the document, then
have a blank line inserted, then my new line of text on a new line
after that. I know VBA fairly well, but don't know the Word object
model very well (as is probably fairly obvious)
The reason you get the error the second time (and probably also have
an extra instance of Word in memory), is most likely becuase you're
using an unqualified reference to the Word Selection object.
Here's some more info
http://support.microsoft.com/kb/319832
http://support.microsoft.com/default.aspx?kbid=178510
There might also be some problems related to the implicit referencing
through ActiveDocument, which sometimes might give additional
challenges.
I'm worndering - you're saying that you wish to add to existing
documents, but you're using the .Add method of the documents
collection, which will create a new document. Did you mean to use
the .Open method?
Try
Dim oWord As Word.Application
Dim oDoc As Word.Document
Set oWord = CreateObject("Word.Application")
Set oDoc = objWord.Documents.Open(docName)
oDoc.Select ' select contents of doc
With oWord.Selection
.EndKey Unit:=wdStory ' move cursor to the end
.TypeParagraph ' add paragraph/line
.TypeText Text:=newText
.TypeParagraph ' add paragraph/line
End With
oDoc.Save
oDoc.Close
set oDoc = nothing
oWord.Quit
Set oWord = Nothing