<

How to generate MS Word Document using VBA


This article tells that how to generate a new word document using VBA Code in MS Access; the document will manage some text inside the document. Also you can figure out that how to include the Header and Footer in the document through the code.

Here's an example, explained to resolve these issue that How to create a new Word Document with Header and Footer.

In the Example shown below in Fig. 1.1, To generate a new word document.

How to generate MS Word Document using VBA Fig-1.1

Fig-1.1

VBA Code for this procedure is shown below:-


Public Function CreateWordDoc()
objWord As Word.Application
Dim doc As Word.Document
Dim WordHeaderFooter As HeaderFooter

'------------------This will generate new MS Word Document-------------

Set objWord = CreateObject("Word.Application")
With objWord
  .Visible = True
  Set doc = .Documents.Add
   doc.SaveAs CurrentProject.Path & "\TestDoc.doc"
End With

'------------------Set properties for Created document file-------------

With objWord.Selection
  .Font.Name = "Trebuchet MS"
  .Font.Size = 16
  .TypeText "This is new word document created through VBaA Code." & " - Font size is " &
  .Font.Size
  .TypeParagraph

'------------------Add header and footer-------------

  ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Text = "Header"
   ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range.Text = "Footer"
End With
doc.Save
doc.Activate
End Function

NOTE:- Don't forget to add reference for Microsoft Word Object

A new blank document will be generated with the default settings. As shown below in Fig: - 1.2.

How to generate MS Word Document using VBA Fig-1.2

Fig-1.2

Fig:- 1.3 show the document with some settings done through code that are Text Type is set to "Trebuchet MS" and Font size is "16".Also managing some text inside and including Header and Footer.

How to generate MS Word Document using VBA Fig-1.3

Fig-1.3

Fig 1.4 show the footer of the document, Header and Footer will remain same for all the pages with in the document.

How to generate MS Word Document using VBA Fig-1.4

Fig-1.4


DISCLAIMER

It is advised that the information provided in the article should not be used for any kind formal or production programming purposes as content of the article may not be complete or well tested. Access Guru will not be responsible for any kind of damage (monetary, time, personal or any other type) which may take place because of the usage of the content in the article.