Class: Word in Category Microsoft Word : Automation from Total Visual SourceBook

Use Microsoft Word Automation to create, edit, save, and output Microsoft Word documents from VBA and VB6.

Word supports interacting with it as an automation server, and for working with documents. Create new or open a Word document, add paragraphs and text, set formatting settings, import files, insert Access data from tables, save, print, preview, and password protect the Word document, create PDF files.

Procedure Name Type Description
(Declarations) Declarations Declarations and private variables for the CWord class.
appWord Property Get a handle to the Word application.
CurDocument Property Get a handle to the current document.
DocumentProperties Property Get the specified document property.
CloseDocument Method Close the current document.
CloseWord Method Close the instance of Word.
CreateTableFromAccess Method Retrieve the contents from a Microsoft Access table or query and place it into a Word table in the current document.
CreateTableFromAccessFormatted Method Retrieve the contents from an Access table or query and place it into a table in the current document with style formatting options.
InsertLines Method Insert one or more blank lines.
InsertText Method Insert text at the current insertion point into the current document.
InsertParagraph Method Insert a paragraph at the current insertion point into the current document.
GoToEnd Method Go to end of the document.
GoToStart Method Go to start of the document.
InsertPageBreak Method Insert a page break at the end of the current range.
InsertTextFromFile Method Insert text from a text file into the current document.
NewDocument Method Create a new word document.
OpenDocument Method Open the named Word file (document).
OpenWithDialog Method Open a file by interacting with a Word dialog.
Note: This method does not set the newly opened document to the class current document.
PrintDocument Method Print the current document.
PreviewDocument Method Preview the current document for printing.
PrintDocumentEX Method Print the current document using extended parameters.
SaveCurrent Method Save the current document.
SaveAsPDF Method Save current file as a PDF file.
SaveCurrentAs Method Save the current document under a new name.
SearchAndReplace Method Run search and replace on the current document with the specified options.
SetWindowState Method Set the Window state for the Word application.
StartWord Method Start an instance of Microsoft Word. Multiple instances of Word can be opened at one time, or you can have one instance of Word open with multiple documents in it.
IsOpen Method Determine if Microsoft Word is already open.
' Example of CWord
'
' To use this example, create a new module and paste this code into it.
' Then run the procedure by putting the cursor in the procedure and pressing:
'    F5 to run it, or
'    F8 to step through it line-by-line (see the Debug menu for more options)

Private Sub Example_CWord()
  ' Comments: Example of using the CWord class to automate Microsoft Word from VBA and VB6.

  ' This example assumes that the sample files are located in the folder defined by the following constant.
  Const cstrSamplePath As String = "C:\Total Visual SourceBook 2013\Samples\"
  Const cstrSampleDB As String = cstrSamplePath & "SAMPLE.MDB"
  Const cstrSampleText As String = cstrSamplePath & "TestWord.txt"
  Const cstrSamplePDF As String = cstrSamplePath & "TestWord.pdf"
  Const cstrTempDoc1 As String = cstrSamplePath & "TestWord1.docx"
  Const cstrTempDoc2 As String = cstrSamplePath & "TestWord2.docx"
  Const cstrSampleTable As String = "tblInteropSample"
  Const cstrPassword As String = "secret"
  Const cfNewInstance As Boolean = True        ' Change to False to use an existing instance of Word, if it's open

  Dim strMsg As String
  Dim clsWord As CWord
  Dim fContinue As Boolean
  Dim fKeepOpen As Boolean

  ' By default, close Word when the example is completed
  fKeepOpen = False

  ' Initialize Word class
  Set clsWord = New CWord

  ' Before continuing, we want to be sure that the computer doesn't have an existing instance of Excel running.
  ' This is so our example code doesn't erroneously interact with the wrong instance of Excel and cause problems.
  If clsWord.IsOpen() Then
    strMsg = "Word is currently open. To avoid modifying your document, close Word before continuing." & vbCrLf & vbCrLf & "Do you want to continue?"
    fContinue = (MsgBox(strMsg, vbYesNo + vbQuestion) = vbYes)
  Else
    ' PowerPoint isn't open, so no need to prompt the user
    fContinue = True
  End If

  If fContinue Then
    ' Ask if the Word documents should be kept open so you can see them
    fKeepOpen = (MsgBox("Do you want to keep Microsoft Word open so you can look at the documents?", vbQuestion + vbYesNo) = vbYes)

    ' Clean up any temp files from a previous run of this example
    DeleteFile cstrTempDoc1
    DeleteFile cstrTempDoc2
    DeleteFile cstrSamplePDF

    ' Start a new instance of Microsoft Word and make it visible (you can use False to have it hidden)
    If clsWord.StartWord(cfNewInstance, True) Then

      ' Create a new document and save it (leaving it open)
      clsWord.NewDocument cstrTempDoc1, "Arial Black", 12

      ' Insert paragraphs and specify its style:
      clsWord.InsertParagraph "Total Visual SourceBook Word Automation", "Title"
      clsWord.InsertParagraph "Examples of Creating a Word Document from VBA/VB6 Code", "Heading 1"
      clsWord.InsertParagraph "Add regular text using Normal style.", "Normal"

      ' Insert text without going to the next line
      clsWord.InsertText "Initial text."
      clsWord.InsertText " Add text to the same line then start another paragraph.", True

      ' Insert a blank line
      clsWord.InsertLines

      clsWord.InsertTextFromFile cstrSampleText

      ' Insert a blank line
      clsWord.InsertLines

      ' Get the first ten records from an Access database and put the field names in bold
      clsWord.CreateTableFromAccess cstrSampleDB, cstrSampleTable, True, 10

      ' Insert a page break
      clsWord.InsertPageBreak

      ' Additional formatting for Access tables: Header of field names is always shown with control over font name and sizes. First 10 records are shown.
      clsWord.CreateTableFromAccessFormatted cstrSampleDB, cstrSampleTable, False, "Tahoma", 16, "Courier New", 9, 10

      ' Insert two blank lines
      clsWord.InsertLines 2

      ' Save the file
      clsWord.SaveCurrent

      ' Save the Word doc as another file name and give it a password
      clsWord.SaveCurrentAs cstrTempDoc2, wdFormatDocumentDefault, True, cstrPassword

      ' Close the document (cstrTempDoc2) to show the example later of opening a document with a password
      clsWord.CloseDocument False

      ' ==========================================

      ' Open the Word document with a password
      clsWord.OpenDocument cstrTempDoc2, cstrPassword

      ' Preview the document
      clsWord.PreviewDocument

      ' Create a PDF file from the document
      clsWord.SaveAsPDF cstrSamplePDF

      If MsgBox("Do you want to print the document?", vbQuestion + vbYesNo) = vbYes Then
        ' Print the document using the simple form
        clsWord.PrintDocument

        ' Print with options specified
        clsWord.PrintDocumentEX True, True, False, True, True, False, False, 1, 99
      End If

      ' Replace just the first occurrence of 'Automation' with 'Programming'
      clsWord.SearchAndReplace "Automation", "Programming", False, True, False, False

      ' Replace every occurrence of 'a' with 'B'
      clsWord.SearchAndReplace "a", "B", False, False, False, True

      ' Resize the window
      clsWord.SetWindowState wdWindowStateNormal, 500, 500

      ' Set the document properties
      clsWord.DocumentProperties(wddpAuthor) = Environ("UserName")
      clsWord.DocumentProperties(wddpCategory) = "(category)"
      clsWord.DocumentProperties(wddpComments) = "Created " & Now
      clsWord.DocumentProperties(wddpCompany) = "(company)"
      clsWord.DocumentProperties(wddpKeywords) = "Word, Example, Total Visual SourceBook, CWord"
      clsWord.DocumentProperties(wddpManager) = "(manager)"
      clsWord.DocumentProperties(wddpSubject) = "Total Visual SourceBook Sample"
      clsWord.DocumentProperties(wddpTitle) = "Automation Example"

      ' Get the document properties
      Debug.Print "DocumentProperties: Getting document properties"
      Debug.Print clsWord.DocumentProperties(wddpAuthor)
      Debug.Print clsWord.DocumentProperties(wddpCategory)
      Debug.Print clsWord.DocumentProperties(wddpComments)
      Debug.Print clsWord.DocumentProperties(wddpCompany)
      Debug.Print clsWord.DocumentProperties(wddpKeywords)
      Debug.Print clsWord.DocumentProperties(wddpManager)
      Debug.Print clsWord.DocumentProperties(wddpSubject)
      Debug.Print clsWord.DocumentProperties(wddpTitle)

      If fKeepOpen Then
        ' Open the previous document to review it after the example is completed
        clsWord.OpenDocument cstrTempDoc1

        ' Maximize Word
        clsWord.SetWindowState wdWindowStateMaximize

        MsgBox "Go to Word to see the documents that were generated"
      Else
        ' Close the document and discard the changes
        clsWord.CloseDocument False
      End If
    End If
  End If

  If Not fKeepOpen Then
    ' Close Word
    clsWord.CloseWord
  End If

  Set clsWord = Nothing

End Sub

Private Function DeleteFile(strFile As String) As Boolean
  ' Comments: Delete the named file, handling errors if the file does not exist (same as KillFile but provided with a similar name)
  ' Params  : strFile           Path and name of the file to delete
  ' Returns : True if the file no longer exists, False if it couldn't be deleted
  ' Source  : Total Visual SourceBook

  Dim fKilled As Boolean

  On Error Resume Next

  Kill strFile

  Select Case Err.Number
    Case 0, 53
      ' Error 53 File not found occurs if the file doesn't exist, which is okay since it's already gone.
      fKilled = True
    Case Else
      fKilled = False
  End Select

  On Error GoTo 0

  DeleteFile = fKilled

End Function

Total Visual SourceBook The source code in Total Visual Sourcebook includes modules and classes for Microsoft Access, Visual Basic 6 (VB6), and Visual Basic for Applications (VBA) developers. Easily add this professionally written, tested, and documented royalty-free code into your applications to simplify your application development efforts.

Total Visual SourceBook is written for the needs of a developer using a source code library covering the many challenges you face. Countless developers over the years have told us they learned some or much of their development skills and tricks from our code. You can too!

Additional Resources

Total Visual SourceBook CD and Printed Manual

Microsoft Access/ Office 2016, 2013, 2010, and 2007 Version
is Shipping!

New features in Total Visual SourceBook for Access, Office and VB6

Supports Access/Office 2016, 2013, 2010 and 2007, and Visual Basic 6.0!


View all FMS products for Microsoft Access All Our Microsoft Access Products

Reviews

Reader Choice Award for MS Access Source Code Library
Reader Choice

"The code is exactly how I would like to write code and the algorithms used are very efficient and well-documented."

Van T. Dinh, Microsoft MVP

SourceBook Info

Additional Info

Question

 

 

Free Product Catalog from FMS