Word Automation - Automating Word with VBA and VBScript
Word Automation Introduction
Programmers can quickly automate Microsoft office applications by using VBA. And when combined with VBScript, they have a very powerful tool at their disposal.
Edraw Office Viewer Component can host the MS Word within a form or web page. The component also supports the word automation. This article shows how to use Word automation by Edraw Office Viewer Component.
Wrapped Word Automation Methods in Office Viewer Component
Edraw Office Viewer Component has wrapped some common used word automation methods. So the developer can simply call these methods and be unnecessary care of the word automation detail.
boolean WordShowRevisions ([in] boolean Show)
Shows/Hides the revisions for the office program.
boolean WordAcceptAllRevisions ([in] boolean Receipt)
Accepts or rejects all the tracked changes in a document or range.
long WordGetBookmarkCount()
Returns the number of bookmarks.
BSTR WordReadBookmarkInfo([in] long Pos, [in] boolean
NameOrValue)
Returns the name or value of the
special bookmark.
Pos: The index of bookmarks in the document. From 1 to ...
NameOrValue: True returns the bookmark name, False returns
the bookmark value.
Example:
The following java script shows how to read the bookmark information.
function Readbookmark_Example ()
{
Var count = edword.GetBookmarkCount();
For(int i=1; i<=count; i++)
{
Var name = edword.GetBookmarkInfo(i, true);
Var value = edword.GetBookmarkInfo(i, false);
}
boolean WordWriteBookmarkInfo([in] BSTR Name, [in] BSTR Value)
Writes the value for the special
bookmark.
Name: The bookmark name.
Value: The bookmark value.
boolean WordInsertFile([in] BSTR FilePath, [in, optional] VARIANT InDocPos)
Inserts a file to opened Word file.
FilePath: The file path needs to be inserted.
InDocPos: The insert position. WdInPocPos.
enum WdInDocPos
{
wdInDocumentPosCursor = 1,
wdInDocumentPosStart = 2,
wdInDocumentPosEnd = 3 ,
}WdInDocPos;
boolean WordInsertText([in] BSTR Text, [in, optional] VARIANT InDocPos)
Inserts text content to opened Word
file.
Text: The text string needs to be inserted.
InDocPos: The insert position. WdInPocPos.
enum WdInDocPos
{
wdInDocumentPosCursor = 1,
wdInDocumentPosStart = 2,
wdInDocumentPosEnd = 3 ,
}WdInDocPos;
boolean WordInsertPicture([in] BSTR FilePath, [in] boolean InlineObject, [in, optional] VARIANT InDocPos)
Inserts a picture to opened Word file.
FilePath: The image path needs to be inserted.
InDocPos: The insert position. WdInPocPos.
enum WdInDocPos
{
wdInDocumentPosCursor = 1,
wdInDocumentPosStart = 2,
wdInDocumentPosEnd = 3 ,
}WdInDocPos;
boolean WordInsertBreak([in] WdBreakType BreakType)
Inserts a break to opened Word file.
BreakType: The break type. WdBreakType.
typedef enum WdBreakType
{
wdPageBreak = 7,
wdColumnBreak = 8,
wdSectionBreakNextPage = 2,
wdSectionBreakContinuous = 3,
wdSectionBreakEvenPage = 4,
wdSectionBreakOddPage = 5,
wdLineBreak = 6,
wdLineBreakClearLeft = 9,
wdLineBreakClearRight = 10,
wdTextWrappingBreak = 11,
}WdBreakType;
Example
The following java script shows how to insert a line break.
function InsertBreak_Example ()
{
Edword.WordInsertBreak(6);
}
boolean WordGotoItem([in] WdGoToItem What, [in] WdGoToDirection Which, [in, optional] VARIANT Count, [in, optional] VARIANT Name)
Goes to the specified item in the Word
document.
What: Optional Object. The kind of item to which the range
or selection is moved. Can be one of the WdGoToItem
constants.
Which: Optional Object. The item to which the range or
selection is moved. Can be one of the WdGoToDirection
constants.
Count: Optional Object. The number of the item in the
document. The default value is 1.
Only positive values are valid. To specify an item that
precedes the range or selection, use wdGoToPrevious as the
Which argument and specify a Count value.
Name: Optional Object. If the What argument is
wdGoToBookmark, wdGoToComment, wdGoToField, or wdGoToObject,
this argument specifies a name.
enum WdGoToItem
{
wdGoToStart = 101,
wdGoToEnd = 102,
wdGoToBookmark = -1 ,
wdGoToComment = 6 ,
wdGoToEndnote = 5 ,
wdGoToEquation = 10 ,
wdGoToField = 7 ,
wdGoToFootnote = 4 ,
wdGoToGrammaticalError= 14 ,
wdGoToGraphic = 8 ,
wdGoToHeading= 11 ,
wdGoToLine = 3 ,
wdGoToObject = 9 ,
wdGoToPage = 1 ,
wdGoToPercent = 12 ,
wdGoToProofreadingError = 15 ,
wdGoToSection = 0 ,
wdGoToSpellingError = 13 ,
wdGoToTable = 2 ,
}WdGoToItem;
enum WdGoToDirection
{
wdGoToAbsolute = 1,
wdGoToFirst = 1,
wdGoToLast = -1 ,
wdGoToNext = 2 ,
wdGoToPrevious = 3 ,
wdGoToRelative = 2 ,
}WdGoToDirection;
Example
The following java script shows how to go to the file end.
function GoToItem_Example ()
{
Edword.WordGoToItem(102, 1);
}
boolean WordReplaceText([in] BSTR Text, [in] BSTR ReplaceText, [in] boolean MatchWholeWord, [in] boolean MatchCase)
Replaces all the specified string value
with another string value.
Text: Optional Object. The text to be searched for.
ReplaceText: The replacement text.
MatchCase: Optional Object. True to specify that the find
text be case-sensitive. Corresponds to the Match case check
box in the Find and Replace dialog box (Edit menu).
MatchWholeWord: Optional Object. True to have the find
operation locate only entire words, not text that's part of
a larger word. Corresponds to the Find whole words only
check box in the Find and Replace dialog box.
boolean WordMergeAndCompare([in] BSTR TargetFilePath)
Compares and merges documents then
displays it in the current windows.
TargetFilepath: Required String.
boolean WordDisableDragAndDrop(boolean Disable)
Disables drag and drop.
long WordGetRevisionCount()
Returns the number of Revisions.
BSTR WordReadRevisionInfo([in] long Pos, [in] WdRevisionType RevType)
Returns the name or value of the
special bookmark.
Pos: The index of bookmarks in the document. From 1 to ...
RevType: The revision type. WdRevision.
enum WdRevisionType
{
wdRevisionAuthor = 0,
wdRevisionDate = 1,
wdRevisionType = 2,
wdRevisionText = 3,
}WdRevisionType;
Example
The following java script shows how to read the bookmark information.
function ReadRevision_Example ()
{
Var count = edword.WordGetRevisionCount();
For(int i=1; i<=count; i++)
{
Var author = edword.WordReadRevisionInfo(i, 0);
Var text = edword. WordReadRevisionInfo (i, 3);
}
boolean WordAcceptRevision([in] long Pos, [in] boolean Accept)
Accepts or rejects the specified
tracked change.
Pos: The index of bookmarks in the document. From 1 to ...
Accept: Accepts or rejects the revision.
boolean WordDisableViewRightClickMenu(boolean Disable)
Disables the right click menu in the MS
Word.
boolean WordCopyToClipboard()
Copies the whole content to the clipboard.
boolean WordCopyToClipboardAsPicture()
Copies the whole content to the clipboard as a picture.
boolean WordPasteFromClipboard([in, optional] VARIANT InDocPos)
Pastes to the opened Word file from the
clipboard data.
InDocPos: The position. WdInDocPos.
enum WdInDocPos
{
wdInDocumentPosCursor = 1,
wdInDocumentPosStart = 2,
wdInDocumentPosEnd = 3 ,
}WdInDocPos;
boolean WordPasteSpecialFromClipboard([in] WdPasteDataType lFormatType, [in] boolean vFloatOverText, [in, optional] VARIANT InDocPos)
Pastes to the opened Word file from the
clipboard data with special format.
lFormatType: Paste format type. WdPasteDateType.
vFloatOverText: True = float the object over text.
InDocPos: The position. WdInDocPos.
enum WdPasteDataType
{
wdPasteBitmap = 4,
wdPasteDeviceIndependentBitmap = 5,
wdPasteEnhancedMetafile = 9,
wdPasteHTML = 10,
wdPasteHyperlink = 7,
wdPasteMetafilePicture = 3,
wdPasteOLEObject = 0,
wdPasteRTF = 1,
wdPasteShape = 8,
wdPasteText = 2,
}WdPasteDataType;
Automating Word with VBA and VBScript
An Automation object is a COM object implementing the IDispatch interface. Automation objects are referred to as ActiveX objects, while an application that manipulates an ActiveX object is referred to as an ActiveX Client. This interface exposes four methods, the most important of which is Invoke. This method allows calling methods of a class by name, with an arbitrary number of parameters. Neither the name of the method nor the number of parameters need to be known at compile time, as it is the case for COM objects not supporting Automation. Moreover, in scripting languages there is no "compile time" at all. This technique is called late binding. Most existing COM components are Automation-compliant and furthermore allow both late binding and traditional, compile-time early binding. This is achieved by implementing so-called dual interfaces, which are interfaces derived from IDispatch. Generally, both late and early binding expose the same functionality for Automation clients; languages such as Visual Basic and Delphi, as well as some C++ libraries, which provide a higher level of abstraction for COM, make sure that all Automation components created in these languages correctly duplicate their interfaces with late and early binding. Many developers are familiar with the word application in VB, C#, VC or Delphi. That is very good. It will help you get started rapidly to write code using word automation capabilities in office viewer component.
Firstly, you can get the Document or Application object by calling the ActiveDocument method.
IDispatch* ActiveDocument();
Returns the Automation interface of the document object.
The method allows you to obtain a reference to the IDispatch interface of the embedded object. From this interface you can automate the object to perform tasks, edit parts of the document, or gather information about what a user has added or removed.
For example, you can insert a table in the word document:
<script language="javascript">
function VBAProgramming()
{
if(document.OA1.IsOpened)
{
if(document.all.OA1.GetCurrentProgID() == "Word.Application"){
var objWord = document.OA1.ActiveDocument;
var range = objWord.Range(0,0);
var WTable = objWord.Tables.Add(range, 3,3);
WTable.Cell(1,1).Range.Font.Name = "Times New Roman";
WTable.Cell(1,1).Range.Text = "Automation 1";
WTable.Cell(1,2).Range.Font.Size = 18;
WTable.Cell(1,2).Range.Bold = true;
WTable.Cell(1,2).Range.Font.Italic = true;
WTable.Cell(1,2).Range.Text = "Automation 2";
WTable.Cell(2,1).Range.ParagraphFormat.Alignment = 1; // 0= Left, 1=Center,
2=Right
WTable.Cell(2,1).Range.Font.Name = "Arial";
WTable.Cell(2,1).Range.Font.Size = 12;
WTable.Cell(2,1).Range.Bold = false;
WTable.Cell(2,1).Range.ParagraphFormat.Alignment = 2;
WTable.Cell(3,3).Range.Font.Name = "Times New Roman";
WTable.Cell(3,3).Range.Font.Size = 14;
WTable.Cell(3,3).Range.Bold = true;
WTable.Cell(3,3).Range.Font.Underline = true;
WTable.Cell(3,3).Range.ParagraphFormat.Alignment = 0;
WTable.Cell(3,2).Range.Text = "Automation 3";
}
else if(document.all.OA1.GetCurrentProgID() == "Excel.Application"){
var objExcel = document.OA1.GetApplication();
var worksheet = objExcel.ActiveSheet;
worksheet.cells(1,1).value ="100";
worksheet.cells(1,2).value ="101";
worksheet.cells(1,3).value ="102";
worksheet.cells(2,1).value ="103";
worksheet.cells(2,2).value ="104";
worksheet.cells(2,3).value ="105";
}
}
}
</script>
IDispatch* GetApplication();
Returns the Automation interface of the application.
In this program, we'll use Word object. We'll use two objects, one of the Word Application class and one of the Word Document class. We'll open the Word Application and a document. User will be able to save the document. Follow the steps below to create the application:
Start a new EXE project. Select Microsoft Word 9.0 object library from the references dialog box. Remember, you should have Word instance on your system. Add a new module to the project. In the module's general declarations section, add the following code.
Replace Text with Edraw Office ViewerComponent
You can use the office automation to replace text with the component.
javascript code:
vbscript code:
Set objWord = document.OA1.GetApplication
Set objSelection = objWord.Selection
objSelection.Find.ClearFormatting
objSelection.Find.Replacement.ClearFormatting
objSelection.Find.Text = varFind
objSelection.Find.Replacement.Text = varReplace
objSelection.Find.Forward = True
objSelection.Find.Wrap = 1 'wdFindContinue
objSelection.Find.Format = False
objSelection.Find.MatchCase = False
objSelection.Find.MatchWholeWord = False
objSelection.Find.MatchWildcards = False
objSelection.Find.MatchSoundsLike = False
objSelection.Find.MatchAllWordForms = False
objSelection.Find.Execute
Conclusion
This article shows you how to use Word automation to enhance the Office Viewer Component and how to call the wrapped word automation methods to realize word automation.
Embedding MS Word in VB.NET and Automating Word
Embed MS Excel in VB 6 and Do the Excel Automation
Disable the Save, Print and Copy Hotkey
Integrate MS Office in Delphi Program
Embed Office in C# and Do Office Automation