How To Automate Microsoft Word From Visual Basic

Feb 09, 2017  Word enables you to add VB code into your document with the help of micro. If you are familiar with vb, then think! What the power you all have? You can do the entire task which is.

-->

Summary

When developing an application that uses data in an Office document, it might be beneficial to have that data presented directly within your Visual Basic application so that the user can see and edit the data without having to switch to the Office application. You can accomplish this in Visual Basic using the OLE Container Control.

This article demonstrates how to dynamically create and Automate an Office document using the OLE Container Control.

More Information

The ability to insert an Office document into Visual Basic is made possible by Microsoft's Object Linking and Embedding (OLE) technology. OLE is designed to let one application host an object belonging to another application in a manner that is convenient for the end user, but doesn't require the applications involved to know the internal details of the other. Visual Basic provides the OLE Container Control to let Visual Basic programmers add OLE objects to a form.

Once the object is embedded, most OLE servers support Automation to let the host application programmatically change or manipulate the object from code. To get a reference to the Automation object, use the Object property of the OLE container. This property returns the Automation object that closely matches the particular item embedded.

Create a Visual Basic application that hosts an Excel workbook

  1. Start Visual Basic and create a new standard project. Form1 is created by default.

  2. From the control toolbox, add three Command Buttons to Form1. Then add an instance of the OLE Container control. When the OLE Container control is placed on the form, it prompts you for the type of object you want to insert. For this sample, you need to add the object dynamically, so click Cancel to dismiss the dialog without adding an object.

  3. In the Code window for Form1, add the following code:

  4. Press the F5 key to run the program. Click the Create button. This embeds a new worksheet and Automates Excel to add data directly to the sheet. Note that if you double-click the object, it activates in-place and the user can edit the data directly. Now click Save to save the data to a file and close the OLE object. The Open button lets you open a copy of a previously saved file.

Create a Visual Basic application that hosts a Word document

  1. Start Visual Basic and create a new standard project. Form1 is created by default.

  2. From the control toolbox, add three Command Buttons to Form1. Then add an instance of the OLE Container control. When the OLE Container control is placed on the form, it prompts you for the type of object you want to insert. For this sample, we need to add the object dynamically, so click Cancel to dismiss the dialog without adding an object.

  3. In the Code window for Form1, add the following code:

  4. Press the F5 key to run the program. Click the Create button. This embeds a new document and Automates Word to add data directly to the document. Note that if you double-click the object, it activates in-place and the user can edit the data directly. Now click Save to save the data to a file and close the OLE object. The Open button lets you open a copy of a previously saved file.

Considerations when using the OLE container

  • If you are embedding from an existing file, the data seen inside the OLE Container is a copy of the data on file. Any changes you make are not automatically saved to the same file. While you can use a technique similar to the one above to save the results back to a specific file, not all OLE servers support this capability. It is not considered normal OLE object behavior.

  • If you are 'linking' to a file, the object cannot be activated in-place. Instead, when the user double-clicks the object, the object is opened in the window of the server application. Only embedded objects can be activated in-place.

  • The OLE Container control is data bound aware. If you have an Access 97 or Access 2000 database, you can bind the control to an OLE Object field in the database. When the form is displayed, the data is pulled from the database and displayed for the user to edit. Any editing changes made by the user are automatically saved back to the database when the OLE object is closed.

    To make the OLE Container control data bound, add a Visual Basic Data control and set its DatabaseName property to the database path. Then set the RecordSource to an existing table in the database. Use the OLE control's DataSource property to bind the control to the Visual Basic Data control, and then set the DataField property to point to a particular field in the recordset that contains the OLE object. Visual Basic does the rest.

  • The size and position of the hatched border that displays when the container is made in-place active is determined by the size of the object and the options selected for the OLE control. This border is displayed to mark the boundaries of the editing window. The boundaries of the editing window often do not match the boundaries of the OLE container itself; this behavior is normal for an OLE object. The editing window cannot be programmatically altered from Visual Basic.

  • Some Automation methods might fail to work correctly unless the object has been made in-place active. To programmatically activate an OLE object, use the DoVerb method and specify vbOLEShow (-1) as the verb.

  • You can determine whether a linked or embedded object's menu appears in the container form by setting a form's NegotiateMenus property. If the child form's NegotiateMenus property is set to True and the container has a menu bar defined, the object's menus are placed on the container's menu bar when the object is activated. If the container has no menu bar, or the NegotiateMenus property is set to False, the object's menus do not appear when it is activated. Note that the NegotiateMenus property does not apply to MDI Forms so an MDI Form's menu cannot be merged with those of the activated object. To illustrate menu negotiation, try the following with the sample application you created in the previous section:

    1. Run the application and click the Create button to embed a new document in the OLE container.
    2. Right-click the OLE container and select Edit to in-place activate the object. Note that the menus for the object's application appear because the NegotiateMenus property of Form1 is set to True by default.
    3. Close the Form to end the application.
    4. With Form1 selected, click Menu Editor on the Tools menu.
    5. Create a new top-level menu with the captionFile and the name mnuFile. Set the NegotiatePosition property of this menu to '1-Left.' Create a menu item with the caption Open and the namemnuOpen.
    6. Click OK to close the menu editor.
    7. Once again, run the application and click the Create button to embed a new document in the OLE container.
    8. Right-click the OLE container and select Edit to in-place activate the object. Notice that the menu for Form1 has been merged with the menus for the object's application.

    Visual Basic does not let you control the menu merging process or make changes to the server's menu items when added. However, you can change or modify an Office application's menus through Automation using code similar to the following:

    Please note that some changes might need to be made before the object is made in-place active, otherwise the changes might fail to appear in the merged menu.

    Note This bullet point does NOT apply to Microsoft Office Excel 2007 or to Microsoft Office Word 2007.

  • Visual Basic does not currently support assignment of toolbar space. Thus, docked toolbars do not normally appear when the object is activated. However, it might be possible to display a floating tool window with automation:

    Note This bullet point does NOT apply to Microsoft Office Excel 2007 or to Microsoft Office Word 2007.

  • For programs that require an object to remain in-place active at all times, Microsoft has provided the ActiveX Documents technology. Not all OLE servers are ActiveX Document servers; Microsoft Word, Microsoft Excel and Microsoft PowerPoint are ActiveX Document servers.

    Visual Basic does not support a native control to host ActiveX Documents. However, the WebBrowser control that comes with Internet Explorer (version 3.0 and higher) does support this form of in-place containment. It is possible to use this control to open an Office document as an ActiveX Document. For more information about using the WebBrowser control, please see the following article:

    243058 How To Use the WebBrowser Control to Open an Office Document

  • The SaveToFile method of the OLE container creates a file that can be opened in the OLE container. However, files that are saved with the OLE container's SaveToFile method cannot be opened directly in the corresponding Office application. If you want to save your embedded document to disk so that document can be opened in the target application, use the application's document SaveAs method:

With Edraw office viewer component, it's easy for the vb developers to embed an existing word document in a form then do the word automating.

The developers can also programmatically generate the Word Document by using VB code then embed the MS Word document in a form. Not like other word read write component, Edraw office viewer component works with the full Microsoft Word program features. Almost all of the tasks which we perform on word can be done programmatically like Inserting Table of Contents, Linking documents, Mail Merge, Inserting Documents, Embedding documents, inserting pictures, watermark.. etc.

If you are not familiar in embedding Edraw office component in Visual Bisic, you can refer to the following article firstly.

Starting off, the first step is to include the Word object references to the Solution. Backlink beast for mac. This can be done by right clicking the Reference Folder in the Solution explorer of the project and select Add Reference.

Browse Through the available COM objects and Select Microsoft Office 11.0 Object Library & Microsoft Word 11.0 Object Library. This Word DLL has all the methods which we do to perform the word automation.

Add Edraw Office Viewer Component in a Visual Basic Form.

Automating Microsoft Word in Visual Basic

The key point is how to build the relationship between the Edraw office component and the Microsoft Word Object Module.

In fact, the component provides two methods which return the Application and Document interface of the opened MS Word document. The developers can add the following Key Code in the DocumentOpened event of the component.

KEY CODE

Dim appWord As Word.Application
Set appWord = EDOffice1.GetApplication()
Dim oWordDoc As Word.Document
Set oWordDoc = EDOffice1.ActiveDocument()

Then the developers can do the word automation without any difference.

For Example:

Text Formatting

All the text formatting options available in the Word Application can also be replicated through automation.

oWordDoc.Selection.Font.Bold = 1
oWordDoc.Selection.Font.Color = Word.WdColor.wdColorAqua
oWordDoc.Selection.Font.Italic = 1
oWordDoc.Selection.Font.Underline = Word.WdUnderline.wdUnderlineDashHeavy

Embedding Pictures in Document Header

oWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader
Dim logoCustom As Word.Shape = Nothing
Dim logoPath As String = 'C:Document and SettingsMyLogo.jpg'
logoCustom = oWord.Selection.HeaderFooter.Shapes.AddPicture(logoPath, oFalse, oTrue, oMissing, oMissing, oMissing, oMissing, oMissing)
logoCustom.[Select](oMissing)
logoCustom.Name = 'CustomLogo'
logoCustom.Left = CSng(Word.WdShapePosition.wdShapeLeft)
oWordDoc.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument

Including Page Numbers in Page Footer

Including auto-generated page numbers in the Footer is yet another useful feature which can be simulated in the code.

oWordDoc.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter
oWordDoc.Selection.TypeParagraph()
Dim docNumber As String = '1'
Dim revisionNumber As String = '0'
oWordDoc.Selection.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft
oWordDoc.ActiveWindow.Selection.Font.Name = 'Arial'
oWordDoc.ActiveWindow.Selection.Font.Size = 8
oWordDoc.ActiveWindow.Selection.TypeText('Document #: ' + docNumber + ' - Revision #: ' + revisionNumber)
oWordDoc.ActiveWindow.Selection.TypeText(' & Chr(9) & ')
oWordDoc.ActiveWindow.Selection.TypeText(' & Chr(9) & ')
oWordDoc.ActiveWindow.Selection.TypeText('Page ')
Dim CurrentPage As Object = Word.WdFieldType.wdFieldPage
oWordDoc.ActiveWindow.Selection.Fields.Add(oWord.Selection.Range, CurrentPage, oMissing, oMissing)
oWordDoc.ActiveWindow.Selection.TypeText(' of ')
Dim TotalPages As Object = Word.WdFieldType.wdFieldNumPages
oWordDoc.ActiveWindow.Selection.Fields.Add(oWord.Selection.Range, TotalPages, oMissing, oMissing)
oWordDoc.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument

Inserting Text in the Centre of the Document as Water Mark

Dim logoWatermark As Word.Shape = Nothing
logoWatermark = oWordDoc.Selection.HeaderFooter.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1, 'Enter The Text Here', 'Arial', CSng(60), Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, 0, 0, oMissing)
logoWatermark.[Select](oMissing)
logoWatermark.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue
logoWatermark.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse
logoWatermark.Fill.Solid()
logoWatermark.Fill.ForeColor.RGB = DirectCast(Word.WdColor.wdColorGray30, Int32)
logoWatermark.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin
logoWatermark.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionMargin
logoWatermark.Left = CSng(Word.WdShapePosition.wdShapeCenter)
logoWatermark.Top = CSng(Word.WdShapePosition.wdShapeCenter)
logoWatermark.Height = oWordDoc.InchesToPoints(2.4F)
logoWatermark.Width = oWordDoc.InchesToPoints(6F)

Inserting Table of Contents

Dim oBookmarkTOC As Object = 'Bookmark_TOC'
Dim rngTOC As Word.Range = oWordDoc.Bookmarks.get_Item(oBookmarkTOC).Range
rngTOC.[Select]()
Dim oUpperHeadingLevel As Object = '1'
Dim oLowerHeadingLevel As Object = '3'
Dim oTOCTableID As Object = 'TableOfContents'
oWordDoc.TablesOfContents.Add(rngTOC, oTrue, oUpperHeadingLevel, oLowerHeadingLevel, oMissing, oTOCTableID, oTrue, oTrue, oMissing, oTrue, oTrue, oTrue)

Updating Table of Contents

oWordDoc.TablesOfContents(1).Update()
oWordDoc.TablesOfContents(1).UpdatePageNumbers()