Solved

Call Word Document Template From VB Program

Posted on 2001-08-08
3
2,711 Views
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
etc.

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

0
Comment
Question by:jtrapat1
3 Comments
 
LVL 3

Expert Comment

by:nzjonboy
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.

nzjonboy
0
 
LVL 17

Accepted Solution

by:
inthedark earned 200 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
DoEvents
DoEvents
DoEvents
DoEvents

' show word (optional)
WordApp.Visible = True
DoEvents

' 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
  rs.MoveNext
Loop

' Close data
RS.Close
DB.CLose
Set RS=Nothing
Set db=Nothing

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

MsgBox "Done"

Exit Sub

CreatePage:

' 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

Return
0
 

Author Comment

by:jtrapat1
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)

Here:
'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.ActiveDocument.Bookmarks("BillNum").Select
        MyWord.Selection.Text = txtBillNum
        MyWord.ActiveDocument.Bookmarks("Sponsor").Select
        If RsBill!rules = "1" Then
            MyWord.Selection.Text = "RULES(At the Request of M. of A. " & Trim(txtSponsor) & ")"
        Else
            MyWord.Selection.Text = "M. of A. " & Trim(txtSponsor)
        End If
        MyWord.ActiveDocument.Bookmarks("Title").Select
        MyWord.Selection.Text = Trim(txtTitle) & vbCr & vbLf
        MyWord.ActiveDocument.Bookmarks("Analyst").Select
        MyWord.Selection.Text = Initials
        MyWord.ActiveDocument.Bookmarks("BillNum2").Select
        MyWord.Selection.Text = txtBillNum
        MyWord.ActiveDocument.Bookmarks("Analyst2").Select
        MyWord.Selection.Text = Trim(AnalystArray(1, 2))
        MyWord.ActiveWindow.ActivePane.View.Type = wdPageView
        MyWord.ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
        MyWord.ActiveDocument.Bookmarks("BillNum3").Select
        MyWord.Selection.Text = txtBillNum
        MyWord.ActiveDocument.Bookmarks("SenateStat").Select
        If RsSenateActions.BOF And RsSenateActions.EOF Then
            MyWord.Selection.Text = ""
        Else
            MyWord.Selection.Text = RsSenateActions!Action
        End If
        MyWord.ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
        MyWord.Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext, Name:="1"
        MyWord.Selection.Find.ClearFormatting
        MyWord.ActiveDocument.Save
        MyWord.Width = 600
        MyWord.Height = 440
        MyWord.Left = 0
        MyWord.Top = 0
    End If

Thaks
John
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction While answering a recent question about filtering a custom class collection, I realized that this could be accomplished with very little code by using the ScriptControl (SC) library.  This article will introduce you to the SC library a…
I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
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…

747 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now