Call Word Document Template From VB Program

Posted on 2001-08-08
Medium Priority
Last Modified: 2011-08-24
I'm using VB6 against an SQL Server database.
Our VB app currently uses a MS Word Document as a template for the many documents we have stored on our server.
We do a FileCopy "\\SERVER\FOLDER\orig.doc", FileName
and then set up the fields.

I'm trying to add a macro to this word document but I'm getting very confused.
Now,this document is not saved as a template;it's a word document with labels for the field names.
When I try to add my macro, I open orig.doc,go to Tools>Macro>Visual Basic Editor and then paste the macro in a module.
But these changes get saved back to my template (normal.dot) back in the default directory at C:\Program Files\Microsoft Office\Office\Templates.

Can I add a macro to this word document that we're using as a template;or,do I have to save it as a template?
If so, can I still manipulate this template from VB?
I mean,we're using commands like:
dim wrd as new word.application
set tmp = word.application
application.documents.open filename,,readonly

Will I still be able to control this template thru VB code?
Thanks in advance.

Question by:jtrapat1
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Expert Comment

ID: 6366246
yea you can still control the template through vb, as long as you are using the template name. btw why are you wanting to put a macro into the word template if yuo also want to control the document from elsewhere? I am guessing that the macro runs a query and puts the results in bookmarks around the document. you can do all this from the other location.

LVL 17

Accepted Solution

inthedark earned 800 total points
ID: 6367013
Here is some untested demo code which shows how to handle Word templates.  Once you have setup your template you can save it to a location.

The following VB6 example creates a word document from a template then prints a page for each record in an access database.  No doubt you will want to do different things here but you san see how the template becomes a new document which is then saved under a new name.

Set a project reference to DAO 3.6 or 3.5 if using Word 97.
Set a project reference to MS Word

Untested word mailmerge VB example:

Dim WordApp As Word.Application
Dim Doc As Word.Document
Dim DSel As Word.Selection
Dim Range As Word.Range
Dim datafile As Long
Dim fc As Integer ' field count
Dim wrd

Dim DB as DAO.Database
Dim RS as DAO.Recordset
Dim SQL as string

' Open your data
Set DB=Workspaces(0).OpenDatabase("c:\yourdb.MDB")

' Now get the data
SQL="Select * from [YourTable];"

Set RS=DB.Openrecordset(db,sql,dbopensnapshot)

' create an instance to word
Set WordApp = New Word.Application

' give word some time

' show word (optional)
WordApp.Visible = True

' create a new document without a template
'Set Doc = WordApp.Documents.Add

' but its best to setup a template and open like:
Set Doc = WordApp.Documents.Add("C:\templates\yourtemplate.dot", False)

' create a link to the current typing area (known as the selection)
Set DSel = WordApp.Selection

Do While Not RS.EOF
  GoSub CreatePage

' Close data
Set RS=Nothing
Set db=Nothing

' save the document
Doc.SaveAs "C:\windows\Temp\test.doc"
Set DSel = Nothing
Set Range = Nothing
set WordApp=Nothing

MsgBox "Done"

Exit Sub


' setup a style
DSel.Style = Doc.Styles("Normal")

' put the addresses into the page
DSel.TypeText RS("YourNameField")+vbcrlf
DSel.TypeText RS("YourAddress1")+vbcrlf
DSel.TypeText RS("YourAddress2")+vbcrlf
DSel.TypeText RS("YourAddress3")+vbcrlf

' movedown

DSel.TypeText vbCrLf
DSel.TypeText vbCrLf
DSel.TypeText vbCrLf

DSel.TypeText "Dear Chummy," ' or even "Dear " + RS("Salutation")+","

DSel.TypeText vbCrLf

' Change style if you wish
'DSel.Style = Doc.Styles("Your Style Name")

' type some words
DSel.TypeText "Mary had a little lamb" + vbCrLf

' now close of the data this record
' now move to the next page

' Now go to end of document
DSel.Collapse Direction:=wdCollapseEnd '0

' insert a pagebreak
DSel.InsertBreak wdPageBreak


Author Comment

ID: 6368760
Thanks for the tips.

Can you take a look at my code and give me an opinion on whether I should stick with a .doc as a template or switch to a .dot.
I have a project which opens bill files (word documents) in an instance of word when an ole object is double-clicked.

Here's the routine that opens the file in a word instance:

Private Sub BamMSWord_Click()
    Set MyWord = New Application
    MyWord.Documents.Open BamFileName, , BamReadOnly
    MyWord.Visible = True
    MyWord.Width = 600
    MyWord.Height = 440
    MyWord.Left = 0
    MyWord.Top = 0
End Sub

The .doc template is used when a new bill file gets created:
I would need the macro to be inside the word document when it is opened.  
The macro is a simple FileSaveAs() procedure that helps the users to save to their own D:\drives and not on the server (or current directory)

'where orig.doc is the template with some labels on it-
and the fields are setup with bookmarks
  FileCopy "\\POOH\piglet\bams\orig.doc", BamFileName
  Set MyWord = New Word.Application
        BamMSWord.CreateLink BamFileName
        MyWord.Documents.Open BamFileName, , BamReadOnly
        MyWord.Visible = True
        MyWord.Selection.Text = txtBillNum
        If RsBill!rules = "1" Then
            MyWord.Selection.Text = "RULES(At the Request of M. of A. " & Trim(txtSponsor) & ")"
            MyWord.Selection.Text = "M. of A. " & Trim(txtSponsor)
        End If
        MyWord.Selection.Text = Trim(txtTitle) & vbCr & vbLf
        MyWord.Selection.Text = Initials
        MyWord.Selection.Text = txtBillNum
        MyWord.Selection.Text = Trim(AnalystArray(1, 2))
        MyWord.ActiveWindow.ActivePane.View.Type = wdPageView
        MyWord.ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
        MyWord.Selection.Text = txtBillNum
        If RsSenateActions.BOF And RsSenateActions.EOF Then
            MyWord.Selection.Text = ""
            MyWord.Selection.Text = RsSenateActions!Action
        End If
        MyWord.ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
        MyWord.Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext, Name:="1"
        MyWord.Width = 600
        MyWord.Height = 440
        MyWord.Left = 0
        MyWord.Top = 0
    End If


Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction In a recent article (http://www.experts-exchange.com/A_7811-A-Better-Concatenate-Function.html) for the Excel community, I showed an improved version of the Excel Concatenate() function.  While writing that article I realized that no o…
Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question