Automate new Word file and insert autotext

L

leaftye

I'm trying to use Excel to automate the creation of a new Word file
using a premade Word template. It makes the new Word file, but breaks
on the last line where I try to insert my autotext. Please review and
help me fix what I'm doing wrong. Also, if it matters, I also intend to
mailmerge this Word doc to the active Excel file. The autotext
definitely exists, so I must be calling it incorrectly. Thanks for
helping!


Dim objWord As Word.Application

Set objWord = CreateObject("Word.Application")
If Err Then
Set objWord = New Word.Application
End If

objWord.Visible = True
objWord.Activate

objWord.Documents.Add Template:="c:\templates\template.dot",
NewTemplate:=False, DocumentType:=0

objWord.ActiveDocument.AttachedTemplate.AutoTextEntries("FORMS").Insert
Where:=Selection.Range, RichText:=True
 
D

Dave Peterson

Without any testing, maybe your code is getting confused at what Selection you
want--the Selection in MSWord or the Selection in Excel.

Where:=Selection.Range
might be better as:
Where:=objWord.Selection.Range


Maybe you can use some of this stuff that I've saved:

Option Explicit
Sub testme01()

Dim oWord As Object
Dim myWordTemplate As String
Dim testStr As String

myWordTemplate = "c:\msoffice\templates\1033\Elegant Fax.dot"

testStr = ""
On Error Resume Next
testStr = Dir(myWordTemplate)
On Error GoTo 0
If testStr = "" Then
MsgBox myWordTemplate & " doesn't exist"
Exit Sub
End If

On Error Resume Next
Set oWord = GetObject(, "Word.Application")
If Err Then
Set oWord = CreateObject("Word.Application")
End If

oWord.Visible = True
oWord.Documents.Add Template:=myWordTemplate

End Sub
 
L

leaftye

Dave said:
Without any testing, maybe your code is getting confused at what
Selection you
want--the Selection in MSWord or the Selection in Excel.

Whe=Selection.Range
might be better as:
Whe=objWord.Selection.Range

Genius! That did the trick. That last line now reads:

objWord.ActiveDocument.AttachedTemplate.AutoTextEntries("FORMS").Insert
Where:=objWord.Selection.Range, RichText:=True
 
Top