Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…
Suggested Courses

636 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