Microsoft KB Archive/286023

= How to use a VB ActiveX component for Word automation from Internet Explorer =

Article ID: 286023

Article Last Modified on 5/17/2007

-

APPLIES TO


 * Microsoft Office Word 2007
 * Microsoft Office Word 2003
 * Microsoft Word 2002 Standard Edition
 * Microsoft Word 2000 Standard Edition
 * Microsoft Visual Basic, Scripting Edition 5.0
 * Microsoft Visual Basic 6.0 Professional Edition
 * Microsoft Internet Explorer 5.0
 * Microsoft Internet Explorer 5.01
 * Microsoft Internet Explorer 5.5

-



This article was previously published under Q286023



SUMMARY
This article demonstrates how you can use an ActiveX component for client-side Automation of Word from a Web page that is rendered in Internet Explorer. There are several benefits to using an ActiveX component from a Web page instead of script that is embedded in the Web page itself:
 * If you already have Visual Basic code that automates Microsoft Word, you can reuse your code in the browser by converting your Visual Basic project to either an ActiveX EXE or an ActiveX DLL.
 * Word is not marked safe for scripting. Depending on security settings in Internet Explorer, Word Automation code in script may not run or the user may be prompted with a security warning. Assuming that your ActiveX component meets certain guidelines, it may be marked safe for scripting to avoid these security issues.
 * Visual Basic has several features that you cannot use with script in a Web page. For example, one feature that is available to Visual Basic but not to Web page script is the ability to call the Windows application programming interface (API).

A common developer scenario is to present users with a Web page interface for creating a Word document by using data from some external source or logic. Although you can use server-side Word Automation to generate the document and stream it back to the client, there are many drawbacks to using a server-side approach that involves Word Automation. The primary drawback is scalability; Word is a very resource-intensive Automation server and is not recommended for document generation on the Web server.

By using an ActiveX component to perform the document generation at the client, you can move the resource-intensive Word Automation away from the Web server. This is the solution that is presented by the sample ActiveX component that is discussed in this article. Although the sample is specific to Word Automation, the same principles may be applied for automating other Microsoft Office applications, such as Microsoft Excel.



Download the Sample
AutoWord.exe contains the Visual Basic ActiveX DLL project, Word document, and Web pages that are described in this article.

The following file is available for download from the Microsoft Download Center:

Autoword.exe

Release Date: April 17, 2001

For additional information about how to download Microsoft Support files, click the following article number to view the article in the Microsoft Knowledge Base:

119591 How to Obtain Microsoft Support Files from Online Services

Microsoft scanned this file for viruses. Microsoft used the most current virus-detection software that was available on the date that the file was posted. The file is stored on security-enhanced servers that help to prevent any unauthorized changes to the file.

Set up the Sample
After you download Autoword.exe, follow these steps to set up the sample:  Create a folder named Invoice in the virtual root directory of your Web server. (The default virtual root directory is C:\Inetpub\Wwwroot.) Extract the files in Autoword.exe to the Invoice folder.  Open Autoword1.htm in a text or HTML editor and replace references to YourWebServer in all URLs with the name of your Web server. Likewise, replace YourSQLServer in the connection string with the name of your SQL Server that contains the Northwind sample database.

NOTE: If you do not have an available SQL Server with the Northwind sample database, you can modify the connection string to use the Microsoft Access Northwind sample database instead. A connection to the Access Northwind sample database resembles the following: sConn = &quot;provider=microsoft.jet.oledb.4.0; data source=&quot; & _ &quot;C:\Program Files\Microsoft Office\Office10\Samples\Northwind.mdb&quot;  Open Autoword2.htm in a text or HTML editor and replace references to YourWebServer in all URLs with the name of your Web server. Start Internet Explorer. You can browse to http://YourWebServer/invoice/AutoWord1.htm and http://YourWebServer/invoice/AutoWord2.htm to test the script. When you first visit either of these pages, you are prompted to download the ActiveX component.

The sample Visual Basic ActiveX component and script are described in more detail in the sections that follow.

Visual Basic ActiveX Component
The Visual Basic ActiveX component in this sample interacts with Web page script to generate an order invoice document at the user's request. The Web application may allow the ActiveX component to obtain the order information for a given order ID, or the Web application may choose to package the order information as XML and send it to the ActiveX component for processing. In either case, after the component obtains the order information, it can automate Word to build and display the invoice document for the order.

The ActiveX component (AutomateWord) contains a single class, the Invoice class, that exposes three methods:
 * The GetData method uses ActiveX Data Objects (ADO) to extract information about an order in the Northwind sample database. The order information is stored in the m_Data private member variable. The GetData method can be called to let the data extraction occur client-side.
 * The SendData method uses Microsoft XML (MSXML) to fill the m_Data private member variable with the order information that is provided by the caller. SendData expects one parameter that represents a DOMDocument object for the order information. The SendData method can be called to send the order information from the Web page to the component. With this approach, you can use ASP to extract the data server-side and present the client with an XML data island that can be used for the document generation.
 * The MakeInvoice method uses Word Automation to build a document that contains the order information in the m_Data private member variable. A document that is stored on the Web server is used as a starting point for the invoice. The caller may choose to display the completed Word document outside of the browser or save the completed document to a disk for later use.

Invoice.cls Option Explicit

Private Type InvoiceData OrderID As String OrderDate As Date CustID As String CustInfo As String ProdInfo As Variant End Type

Private m_Data As InvoiceData

Public Sub GetData(sOrderID As Variant, sConn As Variant)

Dim oConn As Object, oRS As Object 'Connect to the Northwind database. Set oConn = CreateObject(&quot;ADODB.Connection&quot;) oConn.Open sConn 'Obtain the Customer ID and Order Date. Set oRS = CreateObject(&quot;ADODB.Recordset&quot;) oRS.Open &quot;Select [OrderDate], [CustomerID] from Orders where &quot; & _ &quot;[OrderID]=&quot; & sOrderID, oConn, 3 'adOpenStatic=3 m_Data.OrderID = sOrderID m_Data.OrderDate = CDate(oRS.Fields(&quot;OrderDate&quot;).Value) m_Data.CustID = oRS.Fields(&quot;CustomerID&quot;).Value oRS.Close 'Obtain Customer information. Set oRS = CreateObject(&quot;ADODB.Recordset&quot;) oRS.Open &quot;Select * from Customers Where CustomerID='&quot; & _ m_Data.CustID & &quot;'&quot;, oConn, 3 'adOpenStatic=3 m_Data.CustInfo = oRS.Fields(&quot;CompanyName&quot;).Value & vbCrLf & _ oRS.Fields(&quot;City&quot;) & &quot; &quot; If Not (IsNull(oRS.Fields(&quot;Region&quot;))) Then m_Data.CustInfo = m_Data.CustInfo & oRS.Fields(&quot;Region&quot;).Value & &quot; &quot; End If   m_Data.CustInfo = m_Data.CustInfo & oRS.Fields(&quot;PostalCode&quot;).Value & _ vbCrLf & oRS.Fields(&quot;Country&quot;).Value oRS.Close 'Obtain Product information. Set oRS = CreateObject(&quot;ADODB.Recordset&quot;) oRS.Open &quot;Select ProductName, Quantity, [Order Details].UnitPrice,&quot; & _ &quot;Discount from Products Inner Join [Order Details] on &quot; & _ &quot;Products.ProductID = [Order Details].ProductID &quot; & _ &quot;Where OrderID = &quot; & sOrderID, oConn, 3 'adOpenStatic=3 m_Data.ProdInfo = oRS.GetRows oRS.Close 'Close the connection to the database. oConn.Close

End Sub

Public Sub SendData(oXML As Variant)

'Extract the information from the DOMDocument object oXML and store 'it in the private member variable m_Data.

m_Data.OrderID = oXML.getElementsByTagName(&quot;OrderID&quot;).Item(0).Text m_Data.OrderDate = oXML.getElementsByTagName(&quot;OrderDate&quot;).Item(0).Text m_Data.CustID = oXML.getElementsByTagName(&quot;CustID&quot;).Item(0).Text m_Data.CustInfo = oXML.getElementsByTagName(&quot;CustInfo&quot;).Item(0).Text Dim oItems As Object, oItem As Object Set oItems = oXML.getElementsByTagName(&quot;Items&quot;).Item(0) ReDim vArray(0 To 3, 0 To oItems.childNodes.Length - 1) As Variant Dim i As Integer For i = 0 To UBound(vArray, 2) Set oItem = oItems.childNodes(i) vArray(0, i) = oItem.getAttribute(&quot;Desc&quot;) vArray(1, i) = oItem.getAttribute(&quot;Qty&quot;) vArray(2, i) = oItem.getAttribute(&quot;Price&quot;) vArray(3, i) = oItem.getAttribute(&quot;Disc&quot;) Next m_Data.ProdInfo = vArray

End Sub

Public Sub MakeInvoice(sTemplate As Variant, Optional bSave As Variant) Dim oWord As Object Dim oDoc As Object Dim oTable As Object If IsMissing(bSave) Then bSave = False

'Open the document as read-only. Set oWord = CreateObject(&quot;Word.Application&quot;) Set oDoc = oWord.Documents.Open(sTemplate,, True) 'Fill in the bookmarks. oDoc.Bookmarks(&quot;Customer_Info&quot;).Range.Text = m_Data.CustInfo oDoc.Bookmarks(&quot;Customer_ID&quot;).Range.Text = m_Data.CustID oDoc.Bookmarks(&quot;Order_ID&quot;).Range.Text = m_Data.OrderID oDoc.Bookmarks(&quot;Order_Date&quot;).Range.Text = m_Data.OrderDate 'Fill in the table with the product information. '** Note that the table starts out with three rows -- the first row '  contains headers for the table, the second row is for '  the first set of product data, and the third row contains a total. '  New rows are added for additional products before the &quot;total row&quot;.

Set oTable = oDoc.Tables(1) Dim r As Integer, c As Integer For r = 1 To UBound(m_Data.ProdInfo, 2) + 1 If r > 1 Then oTable.Rows.Add (oTable.Rows(oTable.Rows.Count)) For c = 1 To 4 oTable.Cell(r + 1, c).Range.Text = _ m_Data.ProdInfo(c - 1, r - 1) Next oTable.Cell(r + 1, 5).Formula _ &quot;=(B&quot; & r + 1 & &quot;*C&quot; & r + 1 & &quot;)*(1-D&quot; & r + 1 & &quot;)&quot;, _ &quot;#,##0.00&quot; Next

'Update the field for the grand total and protect the document. oTable.Cell(oTable.Rows.Count, 5).Range.Fields.Update oDoc.Protect 1 'wdAllowOnlyComments=1 If bSave Then 'Save the document as &quot;c:\invoice.doc&quot; and quit Word. Dim nResult As Long nResult = MsgBox(&quot;Are you sure you wish to create the document&quot; & _            &quot; &quot;&quot;c:\invoice.doc&quot;&quot;? If this document already exists, &quot; & _             &quot;it will be replaced&quot;, vbYesNo, &quot;AutomateWord&quot;) If nResult = vbYes Then oDoc.SaveAs &quot;c:\invoice.doc&quot; oDoc.Close False oWord.Quit Else 'Make Word visible. oWord.Visible = True End If End Sub

Using the ActiveX Component from a Web Page
Autoword1.htm demonstrates how you can use the GetData method to let the ActiveX component retrieve the order data client-side and build the document.

Autoword1.htm  <HEAD> <OBJECT ID=&quot;AutoWord&quot; CLASSID=&quot;CLSID:32646EBA-0919-4C2F-94D6-599F46DC34F2&quot; CODEBASE=&quot;http://YourWebServer/invoice/package/AutomateWord.CAB#version=1,0,0,0&quot;> </OBJECT> </HEAD> <BODY> Enter an order id between 10248 and 11077 and click the button to view the invoice for the order: <P/><INPUT TYPE=&quot;text&quot; VALUE=&quot;10500&quot; ID=&quot;OrderID&quot;> <P/><BUTTON ID=&quot;InvoiceButton&quot;>Create Invoice</BUTTON> </BODY>

<SCRIPT Language=&quot;VBScript&quot;>

Function InvoiceButton_OnClick Dim sConn sConn = &quot;Provider=sqloledb;Data Source=YourSQLServer;Initial Catalog=Northwind;UID=sa;&quot; AutoWord.GetData OrderID.Value, sConn AutoWord.MakeInvoice &quot;http://YourWebServer/invoice/invoice.doc&quot; End Function

</SCRIPT> </HTML> The script in Autoword1.htm uses the ActiveX component to display the completed document outside of the browser. You may also choose to save the completed document and display it in the browser; however, doing so requires that the Word document be saved to a disk. The component can save the document as C:\Invoice.doc on the client's local drive. Because the ActiveX component is marked safe for scripting, the client is prompted to confirm the save.

If you want to display the completed document in the browser, change the call to MakeInvoice in Autoword1.htm to the following: AutoWord.MakeInvoice &quot;http://YourWebServer/invoice/invoice.doc&quot;, True window.navigate &quot;c:\invoice.doc&quot; Autoword2.htm demonstrates how you can use the SendData method to send the order data as a DOMDocument object to the ActiveX component for generating the completed document. The DOMDocument is created from an XML data island that resides on the Web page. For the ActiveX component to properly process the order information that is sent by the caller, the XML must be well-formed and structured so that the component can interpret it as order information.

Autoword2.htm <HTML> <HEAD> <OBJECT ID=&quot;AutoWord&quot; CLASSID=&quot;CLSID:32646EBA-0919-4C2F-94D6-599F46DC34F2&quot; CODEBASE=&quot;http://YourWebServer/invoice/package/AutomateWord.CAB#version=1,0,0,0&quot;> </OBJECT> </HEAD> <BODY> <BUTTON ID=&quot;InvoiceButton&quot;>Create Invoice</BUTTON> <XML ID=&quot;DataXML&quot;> <Order> <OrderID>10700</OrderID> <OrderDate>10/10/2000</OrderDate> <CustID>SAVEA</CustID> <CustInfo>Save-a-lot Markets Boise ID 83720 USA</CustInfo> <Items> <Product Desc=&quot;Chai&quot; Qty=&quot;5&quot; Price=&quot;18&quot; Disc=&quot;0.2&quot;/> <Product Desc=&quot;Sasquatch Ale&quot; Qty=&quot;12&quot; Price=&quot;14&quot; Disc=&quot;0.2&quot;/> <Product Desc=&quot;Scottish Longbreads&quot; Qty=&quot;40&quot; Price=&quot;12.5&quot; Disc=&quot;0.2&quot;/> <Product Desc=&quot;Flotemysost&quot; Qty=&quot;60&quot; Price=&quot;21.5&quot; Disc=&quot;0.2&quot;/> </Items> </Order> </XML> </BODY>

<SCRIPT Language=&quot;VBScript&quot;> Function InvoiceButton_OnClick AutoWord.SendData DataXML.XMLDocument AutoWord.MakeInvoice &quot;http://YourWebServer/invoice/invoice.doc&quot; End Function

</SCRIPT> </HTML> In both Autoword1.htm and Autoword2.htm, you should note that the ActiveX component is instantiated by way of an <OBJECT> tag rather than the CreateObject function. The purpose of using the <OBJECT> tag is to enable automatic download of the ActiveX component for users that do not already have the component installed. If a user visits one of these pages and the component is not installed, the component is downloaded from the cabinet (CAB) file at the URL that is indicated in the CODEBASE attribute. Depending on the user's security settings in Internet Explorer, they may first receive a prompt to confirm the download.

NOTE: The CAB file that is included in Autoword.exe was created with the Package and Deployment Wizard for Visual Basic. The ActiveX component in the package is marked safe for scripting and initialization, but is not digitally signed.

For more information on creating Internet component downloads, digital signing, and marking components as safe for scripting and initialization, see the following Microsoft Developer Network (MSDN) Web sites:

Signing and Checking Code with Authenticode

http://msdn2.microsoft.com/en-us/library/ms537364.aspx

Safe Initialization and Scripting for ActiveX Controls

http://msdn2.microsoft.com/en-us/library/Aa751977.aspx

<div class="references_section">