Microsoft Word object

zhaozj2021-02-11  226

table of Contents

Application Application object

Use the Document object

Use the RANGE object

Use the Selection object

Use find and replacement objects

Use Table, Column, Row, and Cell objects

Use other ordinary objects

Determine whether the object is effective

Modify the word command

Use event

Use automatic macro

Use automation

Visual Basic supports an object collection, which corresponds directly to the elements in Microsoft Word 97, and through the user interface, the user is familiar with the vast majority of these elements. For example, the Document object represents an open document, and the Bookmark object represents a bookmark in a document, while the Selection object represents the selected content in a document window pane. In Word, each type of element-document, table, paragraph, bookmark, domain, etc. - can be represented by Visual Basic objects. To automate tasks in Word, you can use the methods and properties of these objects.

For the general content of understanding and using the Microsoft Office 97 object model, please refer to the second chapter "Understanding Object Model" of this book. The object model in Microsoft Office 97 is quite rich in which approximately 180 objects are included. To view the hierarchical diagram of the Word object model, see "Microsoft Word Object" in Help. To obtain a detailed description of a particular object, you can click on the name of the object, or search for a specific object in the "Help" index.

How to display Word Visual Basic Help

To use Word Visual Basic help, you must select "Custom" installation mode during the installation process and select the "Visual Basic Online Help" checkbox for Word. Otherwise, the installer will not install Visual Basic help. If the user has already installed Word, then the setup program can be run again to install the Visual Basic help.

To view the Word Visual Basic Help, you can click on the "Directory and Index" in the "Help" menu in the Visual Basic Editor. In the "Contents" dialog in the Help Top, double click on "Microsoft Word Visual" Basic Reference, then double-click the "Visual Basic Reference". The Help Theme dialog will reappear, showing the directory and index of Microsoft Word Visual Basic.

Application Application object

Also create an Application object while the user starts a Word time. Users can use the properties or methods of the Application object to control or return to the features within the application range, control the appearance of the application window or other aspects of the Word object model. You can use the Application attribute to return to the Word Application object. The following example switches from the view state to the print preview state.

Application.printpreview = true

Some properties of Application objects control the look of the application. For example, if the DisplayStatusBar property is True (true), the status bar is visible if the WindowsTate property value is WDWINDOWSTATEMAXIMIZE, then the application window is in a maximized state. The following example sets the size of the application window on the screen.

WITH APPLICATION

.Windowstate = WDWindowStatenormal

.Height = 450

.Width = 600

End with

The properties of the Application object are also accessible to the lower-level objects in the object level, such as a Windows collection (representing all the current open windows) and Documents collection (representing all currently open documents). Users can use properties, sometimes called visits, access to lower-level objects from the highest level of Application object from the object hierarchy (Document object, Window object, Selection object, etc.). You can use one of the following two examples to open MyDoc.doc. Application. Documents. Open filename: = "c: /docs/mydoc.doc"

Documents. Open filename: = "c: /docs/mydoc.doc"

Because the Document property is shared, the Application attribute is optional. Shared properties and methods do not require Application object qualifiers. To browse a list of shared properties and methods in Object Browser, you can click in the Category bar. The common item will be listed in the Member bar.

Note The Option object contains some properties for controlling WORD shared behavior. Many Option objects The properties of an Option object correspond to the various items in the Option dialog. Option properties using the Application object can return Option objects. The following example sets the options within three applications (because the option attribute is shared, so there is no need for Application attributes in this example).

WITH Application.Options

. Allowdraganddrop = true

.Confirmconversions = false

.MeasurementUnit = wdpoints

End with

Use the Document object

A document object is also created when the user opens or creates a file in Word. Users can open, create, save, activate, or off files using the Document object or Documents collection attributes or methods.

Return to Document object

Users can use syntax documents to return any open documents as a Document object, where INDEX is the name or index number of the document. In the following example, the variable mydoc includes a document object that represents a document called "Report.doc".

Set mydoc = documents ("report.doc")

The index number represents the location of the document in the Documents collection. In the following example, the variable MyDoC contains a Document object that represents the first document in the Documents collection.

Set mydoc = Documents (1)

Note Because the user has changed or closes multiple documents, the index number of a particular document changes, so it is best to use the name of the document to index the Document object in the Documents collection.

In addition to the documentation by the name or index number through the document, you can also use the ActiveDocument property to return a Document object that references the active document (current eye-catching document). The following example shows the name of the activity document; if there is no open document, the sample displays a message.

If Documents. Count> = 1 THEN

Msgbox ActiveDocument. Name

Else

Msgbox "No Documents Are Open"

END IF

Open a document

To open an existing document, you can use the OPEN method. The OPEN method is applied to the Documents collection returned by the Document property. The following example opens the file Test.doc (from the current folder) and launched changes tracking.

Set mydoc = documents. Open (filename: = "Test.doc") MyDoc. TrackRevision = TRUE

Note that the return value of the Open method in the above example is a Document object, which represents the document that is just opened. The file name in this example does not include a path; therefore, it is assumed that the file is in the current folder. But this will result in a runtime error, because once the user creates a different folder with the current folder, Visual Basic can't find the file. However, the user can ensure that the correct file is opened as shown in the following table by indicating the full path.

operating system

FileName parameters

Windows

FileName: = "c: / documents / temporary file.doc"

Macintosh

Filename: = "Hard Drive: Documents: Temporary File"

If the user's macro is only used for a file system, the path separator ("/" or ":") can be specified in the FileName parameter, as shown in the above table. The following example shows a code that is not related to the file system, which can be used to open Sales.doc, and assume that Sales.DoC has saved in the Word's program folder.

Programpath = Options. DefaultFilePath (WDPROGRAMPATH)

Documents. Open filename: = programPath & Application. PathseParetor & "Sales.doc"

The PathseParator property returns the current file system (for example, "/" for the file allocation table for MS-DOS / Windows, or ":" For Macintosh), the correct file separator. The DefaultFilePath property returns the location of the file, such as the path, program folder or the current folder where the document is located.

Errors if the specified file name does not appear in the current folder (if there is no specified path) occurs in the specified folder (if specified), then an error occurs. The following example uses the FileSearch object's properties and methods to determine if the file named "Test.doc" exists in the user's default document folder. If this file is found (FoundFiles. Count = 1), then open it; otherwise, a message is displayed.

Defaultdir = Options. DefaultFilePath (WDDocumentsPath)

WITH Application. FileSearch

.Filename = "Test.doc"

.Lookin = defaultdir

.Execute

If .foundfiles. Count = 1 THEN

Open filename: = defaultdir & application. PathseParetor & "Test.doc"

Else

Msgbox "Test.doc File Was Not Found"

END IF

End with

You can also allow users to select files to open instead of the FileName parameter value of the Open method. As shown in the example below, a Dialog object with WDDIALOGFILEOPEN constants can be used, which indicates the "Open" dialog (in the File menu). The Show method can display and execute the action completed in the "Open" dialog.

Dialogs (WDDIALOGFILEOPEN). SHOW

The Display method is just to display a specific dialog without any more operations. The following example checks the return value of the Display method. If the user clicks on "OK" to close the dialog, return value -1 and open the selected file, the name of the file is saved in the variable fselected.

Set DLG = Dialogs (WDDIALOGFILEOPEN)

Abutton = DLG. DISPLAY

FSelected = DLG. Name

If Abutton = -1 Then

Documents. Open filename: = fselected

END IF

To learn more about how to display the Word dialog, see the contents of the "Show Built-in Word Dialog" section in Help.

To determine if a particular document is open, you can use a for Each ... next statement to list the Documents collection. If the document named "Sample.doc" has been opened, the following example activates it; if it has not been opened, the example opens it.

Docfound = true

For Each Adoccian Documents

IF INSTR (1, Adocc. Name, "Sample.doc", 1) THEN

ADOC. ACTIVATE

EXIT for

Else

Docfound = false

END IF

Next adoc

If DocFound = false the documents. Open_

Filename: = "c: /documents/sample.doc"

You can use the count attribute to determine the number of current open documents. The count property is applied to the Documents collection, you can use the Document property to return to the collection. If there is no open document, the following example displays a message.

If Documents. Count = 0 THEN MSGBOX "No Documents Are Open"

Create and save documentation

To create a new document, apply the Add method to the Documents collection. The following example creates a new document.

Documents. Add

The Add method returns a document created only as a Document object. When a user adds a document, you can set the return value of the add method is an object variable so that the user can reference the new document in its own code. The following example creates a new document and sets its upper distance of 1.25 inches.

DIM MYDOC As Document

Set mydoc = documents. Add

MYDOC. Pagesetup. TopMargin = INCHESTOPOINTS (1.25)

When you save a new document for the first time, you can use the SaveAs method with the Document object. The following example saves the active document called "Temp.doc" in the current folder.

ActiveDocument. Saveas filename: = "Temp.doc"

After the document is saved, the user can use its document name to adjust the Document object. The following example creates a new document and saves it as "1996 Sales.doc". This example then uses a new name to make the index of the document in the Documents collection, and add a form to the document.

Add.saveas filename: = "1996 Sales.doc"

Documents ("1996 Sales.doc"). Tables.Add_

Range: = Selection. Range, NumRows: = 2, NumColumns: = 4

To save changes to a already existing document, you can use the Save method with the Document object. The following instructions saved documents called "Sales.doc". Documents ("Sales.Doc"). Save

If the user uses the Save method with a Save or template that has not been saved, the Save As dialog box will display the user to name the file. To save all open documents, you can apply the Save method for the Documents collection. The following example saves all open documents, but no user is named for the file.

Documents. Save noPrompt: = true

Activate a document

To make another document be an active document, you can apply an Activate method to the Document object. The following example activates the open document (MyDocument.doc).

Documents ("MyDocument.doc"). Activate

The following example opens two documents, and then activates the first document (Sample.Doc).

SET DOC1 = Documents. Open (filename: = "c: /documents/sample.doc")

SET DOC2 = Documents.open (filename: = "c: /documents/other.doc")

DOC1. Activate

Print a document

To print a document, apply the PrintOUT method to the Document object, as shown in the following example.

ActiveDocument. PrintOut

To set the print options that can also be set in the Print dialog (in the File menu) through the program, you can use the parameters of the Printout method. Users can use the properties of the Options object to set the print option, which can also be set in the "Options" dialog (in the Tools menu). The following example sets the active document prints hidden text and only prints the top three pages.

Options. Printhiddentext = true

ActiveDocument: = WDPrintFromTo, from: = "1", to: = "3"

Close the document

To turn off a document, you can apply a Close method to the Document object. The following example turns off document called "Sales.doc".

Documents ("Sales.doc"). Close

If the document is modified, Word will display a message to ask the user to save the modifications. The user can use WDDONOTSAVECHANGES or WDSAVECHANGES constants with the SaveChanges parameter to make this prompt no longer appear. The following example is saved and closed Sales.doc.

Documents ("Sales.doc"). Close SaveChanges: = WDSAVECHANGES

To close all open documents, you can apply a Close method to the Documents collection. All the following examples are not saved to turn off all documents.

Documents: = WDDONOTSAVECHANGES: = WDDONOTSAVECHANGES: = WDDONOTSAVECHANGES

Access to objects in the document

Users can access a series of properties and methods for returning objects from the Document object. To view the hierarchical diagram of the objects that can be used in the Document object, you can see "Microsoft Word Objects (Documents" in Help. For example, a Table property that can return a collection of Table objects that can be used in the Document object. As a count property used by a collection object can determine the number of items included in the collection. The following example shows a message to indicate how many forms in the active document.

MsgBox ActiveDocument. Tables. Count & "Table (s) in this document" You can return a single table object with Table (index), where INDEX is the index number. In the following example, MyTable represents the first table in the "Sales.Doc" document.

Set myTable = documents ("Sales.doc"). Tables (1)

About returning a special object can be obtained from the object topic itself in Help (eg, "Table Object") and the corresponding set object topic (for example, "Table Collection Object").

Add an object to a document

An object such as an footnote, a note or a table can be added to the document with the add-on ADD method that can be accessed in the Document object. For example, the following command adds a 3x3 table to the location specified by myRANGE variable (MyRange is an object variable containing a Range object).

ActiveDocument. Tables. Add range: = 3, numcolumns: = 3

The following example adds a footnote to the location specified by myRANGE variable.

ActiVedocument. AddNotes. Add Range: = MyRange, Text: = "The Willow Tree" a

To get a list of collection objects that support the Add method, see "ADD Method" in Help.

Use the RANGE object

When using Visual Basic, a common task is to specify a zone in the document, then process it, such as inserting text or application format. For example, the user may want to write a macro to position a word or phrase in a portion in a document. Then you can use a Range object to indicate some of the documents you want to search for specific words or phrases. After determining the RANGE object, the user can apply the method and attribute of the object to modify the content in the respective range.

A Range object represents a continuous area in the document. Each Range object is defined by a starting character position and a termination character position. Similar to the user using a bookmark in the document, you can use the RANGE object in Visual Basic to identify a specific part of a document. A Range object can be as small as insertion points, or as large as the entire document. However, unlike bookmarks, the Range object is only in runtime process.

The Range object is independent of the selected content; that is, the range can be defined and modified without changing the selected content. Users can also define multiple ranges in the document, and there is only one selected content in each document pane.

START, END and STORYTYPE properties uniquely determine a RANGE object. The start and End properties return or set the position of the start and end characters of the RANGE object. The character position at which each document is generated is 0 (ZERO), and the position after the first character is 1, and this type is pushed. The WDSTORYTYPE constant of the StoryType property can represent the 11 different documents constitute a part type. For example, if there is a Range object in the footpool area, the StoryType property returns WDFOOTNOTESSSSTORY. To learn more about the document composition, see the relevant contents of the "Application Document Components" section later in this section.

Use the Range object instead of the Selection object

The macro recording system often creates a macro that uses the Selection property to control the manipulating Selection object. However, users can usually use one or several RANGE objects to complete the same task at a very few commands. The following example is created with a macro recorder. This macro is bold to the first two words in the document.

Homekey Unit: = WDSTORY

Selection. Moveright Unit: = wdword, count: = 2, extend: = WDEXTENDSELECTION. Font.bold = wdtoggle

The following example does not use the Selection object to complete the same task.

ActiveDocument. Range (start: = 0, end: = activedocument. Words (2). End) .bold = TRUE

The following example is bold to the first two words in the document and then insert a new paragraph.

Homekey Unit: = WDSTORY

Selection. Moveright Unit: = wdword, count: = 2, extend: = WDEXTEND

SELECTION. Font.bold = wdtoggle

Selection. Moveright Unit: = WDCharacter, count: = 1

Selection. TypeParagraph

The following example does not use the Selection object to complete the same tasks in the above examples.

Set myrange = activeDocument. Range (start: = 0, end: = activedocument. Words (2). End)

MyRange. bold = TRUE

IRANGE. InsertParagraphafter

The two examples of the previous change have changed the format in the active document but did not change the selected content. Under most occasions, the Range object is more desirable than the Selection object, as follows:

Users can define and use multiple RANGE objects, and only one Selection object can be included in each document window.

Control management Range object does not change the selected text content.

Control management Range object is fast than using the Selection object.

Return the RANGE object using the RANGE method

You can create a RANGE object in a specific document using the RANGE method. Range method (can be used from Document object), which is positioned in the main document component, with a given start point and end point. The following example creates a RANGE object and assigns a MyRANGE variable.

Set myrange = activeDocument. Range (start: = 0, end: = 10)

In the above example, MyRange represents the first ten characters in the movable document. When you apply an attribute or method to the Range object saved in your Myrange variable, you can see the Range object that has been created. The following example is bold to the top ten characters in the movable document.

Set myrange = activeDocument. Range (start: = 0, end: = 10)

MyRange. bold = TRUE

When the user needs multiple references to a RANGE object, the SET statement can be used to set a variable equivalent to the RANGE object. However, if the user needs to perform an operation on an object, it is not necessary to save the object to the variable. The user can use a command to determine the range and change the command of the bold property to obtain the same result; as shown below.

ActiveDocument. Range (start: = 0, end: = 10). Bold = true

Similar to bookmarks, a range can span a set of characters in the document, or mark one of them. In the following example, the starting and termination point of the RANGE object is the same, and any text is not included in this range. This example is inserted into the text at the beginning of the active document.

ActiveDocument. Range (start: = 0, end: = 0). INSERTBEFORE TEXT: = "Hello" User can use the START attribute using the character position shown in the example above, or using the START attribute with the Selection object, the Bookmark object, or the Range object and END attributes to define a range of start and termination locations. The following example creates a RANGE object to represent the third and fourth sentences in the movable document.

Set mydoc = ActiveDocument

Set myrange = mydoc. Range (start: = mydoc. Sentences (3). Start, _

End: = mydoc. SENTENCES (4). End)

Skills Range objects are invisible in documentation. However, users can use the Select method to select a RANGE object to ensure that the RANGE object represents the correct text range. The RANGE object in the following example represents the first three paragraphs in the movable document. After the macro is running, the selected content refers to the range of text included in the Arange variable.

Set arange = activeDocument.range (start: = 0, _

End: = activedocument. Paragraphs (3). Range. End)

arange. SELECT

Use the Range property to return a Range object

You can use the RANGE property in many objects, for example, Paragraph objects, Bookmark objects, EndNote objects, and Cell object -Range properties are used to return a RANGE object. The following example returns a RANGE object that represents the first paragraph of the movable document.

Set myrange = ActiveDocument.Paragraphs (1). Range

After creating a reference to the RANGE object, the user can modify this range using any attributes or methods. The following example copies the first paragraph in the activity document.

Set myrange = activeDocument. Paragraphs (1). Range

MyRange. COPY

The following example copies the first line of the table in the active document.

ActiveDocument. Tables (1). ROWS (1). Range. COPY

The following example shows the text from the first bookmark mark in the event document. The Range property can be used in the Bookmark object.

Msgbox ActiveDocument. Bookmarks (1). Range. Text

If the user needs to apply a variety of attributes or methods to the same RANGE object, you can use the with ... End with statement. The following example sets the format of the text as the first segment of the active document.

Set myrange = activeDocument. Paragraphs (1). Range

WITH MYRANGE

.Bold = true

.Paragraphformat. Alignment = WDALIGNPARAGRAPHCENTER

.Nime = "arial"

End with

To get other examples of returning a Range object, see "Range Properties" in Help.

Section part of the document

Visual Basic contains some objects that use them to modify the following types of document elements: characters, words, sentences, paragraphs, and section. The following table contains objects returned to the properties and properties of these document elements.

Episode

Back to the object

Word (INDEX)

Range object

Characters (INDEX)

Range object

SENTENCES (INDEX)

Range object

Paragraphs (Index) Paragraph object

Sections (Index)

Section object

When the user does not with index to use these properties, returns a collection of the same name - for example, the Paragraphs property returns the Paragraphs collection. However, if the user uses index to determine one of a collection, returning the object in the second column of the above table - for example, Words (1) returns a RANGE object. Users can use any range attributes or methods to modify the RANGE object, as shown in the example below, the example copies the first word in the selected content into the clipboard.

Selection. Words (1). COPY

The set items in the Paragraphs collection and the Sections collection are the paragraph object and the section object, not the RANGE object. However, in the Paragraph object and the Section object, you can use the RANGE property (it returns a RANGE object). The following example will obtain the first segment in the document to the clipboard.

ActiveDocument. Paragraphs (1). Range. COPY

All document element properties in the above table can be used in the Document object, Selection object, and the RANGE object, as shown in the following three examples.

This example sets the case in the first word in the activity document.

ActiVedocument. Words (1). Case = WDUPPERCASE

This example sets the next distance from 0.5 inches.

Selection.sections (1). Pagesetup. Bottommargin = Inchestopoints (0.5)

This example sets the text in the active document to twice the line spacing (the Content property returns a RANGE object, which represents the main document component).

ActiveDocument. Content. ParagraphFormat. Space2

Modify a set of document elements

To modify the range consisting of a set of text elements (characters, words, sentences, paragraphs, or festival), you can create a RANGE object containing document elements. With the RANGE object uses the start and end properties, the user can create a new RANGE object that references a set of document elements. The following example creates a RANGE object (MyRANGE), which references the first three words in the active document, and then change the font of these words to Arial.

SET DOC = ActiveDocument

Set myrange = doc.range (start: = doc. Words (1). Start, end: = doc. Words (3). End)

MyRange. font. name = "arial"

The following example creates a RANGE object that starts with the beginning of the second paragraph, and ends after the fourth segment.

Set mydoc = ActiveDocument

Set myrange = mydoc. Range (start: = mydoc. Paragraphs (2). Range. Start, _

End: = mydoc. Paragraphs (4). Range. End)

The following example creates a RANGE object (ARANGE) that starts with the beginning of the second paragraph, and ends after the third paragraph. ParagraphFormat is used to access properties such as SpaceBefore and SpaceAfter.

SET DOC = ActiveDocument

Set arange = DOC. Range (start: = doc. Paragraphs (2). Range. Start, _

End: = DOC. Paragraphs (3). Range. End) with arange. Paragraphformat

.Space1

.SpaceAfter = 6

.SPACEBEFORE = 6

End with

Return or set the text in the range

You can use the text attribute to return or set the contents of a range object. The following example returns the first word in the event document.

Strtext = ActiveDocument. Words (1). Text

The following example changes the first words in the active document to "Hello".

ActiVedocument. Words (1). Text = "Hello"

You can use the INSERTAFTER method or the INSERTBEFORE method to insert a text in front or back. The following example is inserted into the text before the second paragraph of the active document.

ActiveDocument. Paragraphs (2). Range. Insertbefore Text: = "in the beginning"

After using the INSERTAFTER method or INSERTBEFORE method, the range is expanded, including new text. However, you can also fold the range into the starting position or termination location using the collapse method. The following example is inserted into the word "Hello" before the existing document, and then fold the range into its starting position (before the word "Hello").

With activedocument.paragraphs (2) .range

.Insertbefore text: = "Hello"

.COLLLAPSE DIRECTION: = WDCOLLAPSSTART

End with

Set the format of the Chinese word

You can use the font property to get the properties and methods of setting the character format, and use the paragraphformat attribute to get the properties and methods of setting paragraph formats. The following example sets the character format and paragraph format of the first paragraph in the activity document.

WITH ACTIVEDOCUMENT. Paragraphs (1). Range. Font

.Name = "Times New Roman"

.Size = 14

.Allcaps = true

End with

WITH ACTIVEDOCUMENT. Paragraphs (1). Range. ParagraphFormat

.Leftent = inchestopoints (0.5)

.Space1

End with

Redefine Range object

You can use the SetRange method to redefine an existing RANGE object. The following example defines MyRANGE as the current selection. The setRange method redefines myRange so that it represents the current selection content plus the subsequent ten characters.

Set myrange = selection. Range

MYRANGE. SetRange Start: = myrange. start, end: = myrange. End 10

To get other information and examples of redefining the Range object, see "SetRange Method" in Help.

Users can also redefine a RANGE object by changing the value of the start attribute and the END attribute or using the MoveStart method or Movend method. The following example redefines the MyRANGE object so that it represents the current selected content plus the subsequent ten characters.

Set myrange = selection. Range

MYRANGE. END = myrange. end 10

The following example uses the MOveEnd method to extend MyRange so that it contains the next paragraph.

Set myrange = activeDocument. Paragraphs (2)

MyRange. Movend Unit: = WDPARAGRAPH, Count: = 1 Circulation in the range within the range

The cycle can be carried out in a range in a range of several different methods. This section contains contents of cycles in paragraphs within the range using the for Each ... next ... and NEXT attributes and methods. It is also possible to use the same technique to cycle in the range, words or sentences.

Use for Each ... Next statement

It is recommended to use the for Each ... NEXT statement when performing paragraph cycles within the scope, and it is also recommended to use this statement when cycles in the collection. The following example is looped in the first five segments of the document, which is added to each time.

Set mydoc = ActiveDocument

Set myrange = mydoc.range (start: = mydoc. Paragraphs (1). Range. Start, _

End: = mydoc. Paragraphs (5). Range. End)

For Each Para in MyRange. Paragraphs

PARA.RANGE. INSERTBEFORE "Question:" & vbtab

Next Para

Assume that the user wants to modify the above-described code, looping the segment selected by the user within the range. You can use the Selection property to indicate each paragraph in the selected content. The following example loops in the paragraph of the selected content, remove the bold format.

For Each Para in Selection. Paragraphs

Para.range. bold = false

Next Para

Use Next attributes or methods

Users can also use NEXT attributes and methods to loop in the range of paragraphs. The following example illustrates how to loop in the range of words, increase each word a little bit.

Set myrange = activeDocument.words (1)

FOR i = 1 to 5

MyRange. font. size = myrange. font. size i

Set myrange = myrange. Next (unit: = wdword, count: = 1)

Next i

The following example is looped in the range of paragraphs, and the alignment of the range is changed from the center to left alignment. This example also redefines MyRange with the next attribute to indicate the next paragraph.

Set myrange = activeDocument. Paragraphs (1). Range

FOR i = 1 to 5

IFRANGE. Paragraphs (1). Alignment = WDALIGNPARAGRAPHCENTER THEN

MYRANGE. Paragraphs (1). Alignment = WDALIGNPARAGRAPHLEFT

END IF

Set myrange = myrange. Paragraphs (1). Next. Range

Next i

Assign the RANGE object to the variable

You can give a variable by several ways to assign an existing RANGE object. In the following example, variable Range1 and variable Range2 represents the RANGE object. In this example, the command is assigned to the first and second words in the active document to the variables RANGE1 and RANGE2.

Set Range1 = ActiveDocument. Words (1)

SET RANGE2 = ActiveDocument. Words (2)

Set a Range object variable equivalent to another Range object variable

The following example creates a variable Range2 and is the same as RANGE1.

SET RANGE2 = Range1

There are two variables to represent the same range. When the user adjusts the starting position of the RANGE2, the change will also affect the Range1, and vice versa. The following example assigns the value of the RANGE1 default property (Text property) to the default properties of the RANGE2. In this example, the code is equivalent to the Range2. Text = Range1. Text, it does not change the content represented by the RANGE object, which only changes the contents of the RANGE2 (Text).

Range2 = Range1

These two ranges (RANGE2 and RANGE1) include the same content, but they may point to different locations in the document, or simply different documents.

Use the duplicate properties

The following example creates a new replicated RANGE object, Range2, which has the same start position, termination location, and text content like Range1.

SET RANGE2 = Range1. Duplicate

If the starting position of the RANGE1 is changed or the termination position, this change does not affect the RANGE2, and vice versa. However, because these two range points to the same location of the document, change the text content in one range will also change the text content of another range.

Use documentation components

A document component is a region in the document that distinguishes the text from other areas in the document. For example, if a document contains textual text, footnotes, and header, the document contains the document body, the footnote section, and the header section.

You can use the StoryTYPE attribute to return to the specified range, a document component, or a bookmark. If the selected content is included in the footnote section, the following example will close the footnotes pane in the active window.

ActiveWindow. View. Type = WDNORMALMALMALVIEW

If Selection. StoryPE = WDFOOTNOTESSSTORY THEN ActiveWindow. ActivePane. Close

The Storyranges collection contains the first process section of each of the valid documents in a document. You can use the NextStoryRange method to return to the subsequent document components. The following example searches for each document process section in the event document to find the text "Microsoft Word". This example also sets all of the words found each time to italics.

For Each MyStoryRange in ActiveDocument. StoryRanges

MyStoryRange. Find. EXECUTE FINDTEXT: = "Microsoft Word", Forward: = TRUE

While MyStoryRange. Find. Found

myStoryRange. italic = true

MyStoryRange. Find.execute FindText: = "Microsoft Word", _

Forward: = true, Format: = TRUE

Wend

While Not (MyStoryRange. NextStoryRange is nothing)

Set myStoryRange = MyStoryRange. NextStoryRange

MyStoryRange. Find.execute FindText: = "Microsoft Word", Forward: = TRUE

While MyStoryRange. Find. Found

myStoryRange. italic = true

MyStoryRange. Find.execute FindText: = "Microsoft Word", _

Forward: = true, Format: = TRUE

Wend

Wend

Next MyStoryRange

Use the Selection object

When a user uses a document in Word, you will usually choose text, then perform an operation, such as setting with text, or type new text. In Visual Basic, it is usually not necessary to select the text before modifying the text; but create a RANGE object representing a specific part of the document and operates it. However, when the user wants its own code to respond or change the selected content for the selected content, you can complete the task through the Selection object.

You can use the Selection property to return Selection objects. There can be only one Selection object in each pane of the document window. At any time, there can only be an active Selection object. The selected content can contain an area of ​​the document, or it can be folded into an insertion point. The following example changes the paragraph format of each segment in the selected content.

Selection. Paragraphs. Spacebefore = inchestopoints (0.25)

The Selection property can be used in Application objects, Window objects, and PANE objects. If the Selection property is used as the Application object, the Selection object represents the selected content of the activity.

INSERTAFTER TEXT: = "Next Text"

You can also return to a Selection object in a specific window or window pane with a Window object or a PANE object using the Selection property. The following examples use the Selection property with the Window object, insert the text in the Document Window "Document2".

Windows ("Document2"). Selection.Insertafter text: = "new text"

The following examples use the Selection property along with the PANE object, insert the text in the home page.

With activeWindow

.View. Type = WDPAGEVIEW

. Seekview = wdseekprimaryheader

.Ctivepane. Selection. InsertAfter text: = "Header"

End with

After using the INSERTAFTER method or INSERTBEFORE method, the selected content is expanded, including new text. However, the user can also fold the selected content to its start or termination position using the collapse method. The following example is inserted into the word "Hello" after the text of the selected content, and any case where the selected content is folded to the word "Hello".

INSERTAFTER TEXT: = "Hello"

Selection. Collapse Direction: = WDCOLLAPSEEND

Move and expand selection

The user can move or extend the selected content (eg Move and Movend) represented by the Selection object through several ways. The following example moves the selected content to the beginning of the next paragraph.

Selection. MoveDown Unit: = WDPARAGRAPH, Count: = 1, Extend: = WDMOVE

The user can also move or extend the selected content by changing the START attribute of the Selection object and the value of the End property, or by moving or expanding the selected content via the Movestart and Movend methods. The following example extension the selected content by moving the termination position to the tail.

Selection. Movend Unit: = WDPARAGRAPH, Count: = 1

Because there can be only one selected content in a document window or pane, the user can also move the selected content by selecting another object. You can use the SELECT method to select one of the documents. After using the SELECT method, you can return a Selection object using the Selection property. The following example selected the first word in the active document, and then turned the word to "Hello". ActiVedocument. Words (1). Select

Selection. Text = "Hello"

Users can also move selected content via the GotOnext method, GotopeVious method, or goto method. The following example moves the selected content to the fourth line in the document.

Selection. Goto what: = WDGOTOLINE, Which: = WDGOTOABSOLUTE, COUNT: = 4

The following examples move the selected content before the next domain in the active document.

Selection. Gotonext what: = WDGOTOFIELD

Objects used in Selection objects

Many other objects that can be used in the RANGE object and the Document object can also be used in the Selection object, which allows the user to control the manipulation object in a selected content. To get a complete list of objects that can be used in Selection objects, see "Microsoft Word Objects", or "Selection Object" in Help.

The following example updates the results of each domain in the selected content.

IF selection. Count> = 1 Then Selection. Fields. Update

The following example has grown 0.5 inches in each paragraph in the section.

Selection. Paragraphs. Leftindent = inchestopoints (0.5)

The user can loop operation on a single object in the selected content using the for Each ... Next statement, replacing all objects in the selected content, control manipulation one by one. The following example is looped on each paragraph of the selected content, which will change the segment of any homogeneous sects.

For Each Para in Selection. Paragraphs

IF para. Alignment = wdalignparagraphcenter thr. alignment = _

WDALIGNPARAGRAPHLEFT

Next Para

The following example shows the name of each bookmark in the selected content.

For Each Aubook in Selection. Bookmarks

Msgbox online. Name

Next ABOOK

Selection object properties and methods

This section highlights some common attributes and methods of the Selection object.

Return or set the text in the selected content

You can use the text attribute to return or set the content of a Selection object. The following example returns the selected text.

Strtext = Selection. Text

The following example changes the selected text to "Hello World".

Selection. Text = "Hello World"

You can insert text or later in the INSERTBEFORE method or INSERTBEFORE method. The following example is inserted into the text before selecting the content.

INSERTBEFORE TEXT: = "And furthermore"

Set format for many text

You can use the Font property to access properties and methods of setting characters format, or you can use the ParagraphFormat property to access the properties and methods of setting paragraph formats. The following example sets the characters and paragraph formats of the selected content.

WITH SELECTION. FONT

.Name = "Times New Roman"

.Size = 14nd with

Selection. ParagraphFormat. Leftindent = inchestopoints (0.5)

Returns a Range object

If a method or attribute is in a RANGE object rather than (for example, checkspelling method), you can use the range property to return a RANGE object from the Selection object. The following example spells the selected word.

CHECKSPELING

Returns information about selected content

You can use the information attribute to return information about the selected content. For example, the user can determine the page number of the current page, the total number of pages of the document, or whether the selected content is in one header or foot. Information attributes can take thirty-five different constants (WDNumberOfpages Indocument, and WDNHEADERFOOTER, etc.), users can use them to return different information about selected content. For example, if the selected content is in a table, then the following example will display the line number or column number in the table.

IF selection. Information (wdwithintable) = True Then

MsgBox "Column =" & Selection. Information (WDMaximumNumBerOfcolumns)

& VBCR & "ROWS =" & Selection. Information (WDMaxImUMnumberofrow)

END IF

To get a complete list and description that can be used with the information property, see "Information Properties" in Help.

Judging whether the text is selected

You can use the TYPE attribute to set or return the selected content to be specified in the document. For example, a WDSELECTIONBLOCK constant can be used to determine if a text block is selected. If the selected content is an insertion point, then the following example selects the paragraph containing the insertion point.

IF selection. Type = wdselectionip the

Selection. Paragraphs (1). Range. SELECT

END IF

Use find and replacement objects

You can use the Find and Replacement objects to find and replace the specific range of the text in the document. Find objects can be used in Selection objects or RANGE objects (depending on the Find object is returned from the Selection object or from the RANGE object, the lookup operation is slightly different).

Use selection.find

If you use a Find object in the Selection object, the selected content will change when the text that meets the selection criteria will change. The following example selected the word "Hello" that appeared next. If you have reached the end of the document before finding the word "Hello", then stop search.

WITH SELECTION. FIND

.Forward = TRUE

.Wrap = WDFINDSTOP

.Text = "Hello"

.Execute

End with

The Find object contains properties related to the options in the Find and Replace dialogs (in the Edit Menu). The user can set both attributes of the Find object, or with the Execute method to use parameters for settings, if the following example is shown.

SEECUTE FIND. EXECUTE FINDTEXT: = "Hello", Forward: = true, wrap: = WDFINDSTOP

Use Range.Find

If you use a Find object in the RANGE object, the selected content will not change, but the scope of the text that is in line with the selection condition will be redefined. The following example determines the position of the word "Blue" that appears in the active document. If the lookup operation is successful, the range is redefined and the format of the word "Blue" is set is bold. WITH ACTIVEDOCUMENT. Content. Find

.Text = "blue"

.Forward = TRUE

.Execute

If .found = true kil tparent.bold = true

End with

The following example executes the same operation as the above example, except that the parameters of the Execute method are used.

Set myrange = ActiveDocument. Content. Content

MyRange Find. EXECUTE FINDTEXT: = "Blue", Forward: = TRUE

If MYRANGE. FOUND = True Then MyRange. Bold = true

Use the Replacement object

The Replacement object represents the replacement of the lookup-replacement operation. The properties and methods of the Replacement object correspond to the options in the Find and Replace dialog (in the Edit Menu).

You can use the Replacement object in the Find object. The following example replaces all the words "Hi" that appears to "Hello". When you find the text that meets the selection condition, the selected content will change because the code returns a Find object from the Selection object.

WITH SELECTION. FIND

.Clearformatting

.Text = "hi"

.Replacement. ClearFormatting

.Replacement. Text = "Hello"

= WDREPLACEALL, Forward: = true, wrap: = WDFINDCONTINUE

End with

The following example removes all bold formats in the active document. Bold Property For the Find object, true (true), for the Replacement property is false. To find and replace formats, set the lookup and replace the text as an empty string (""), and set the format parameter of the Execute method to True. The selected content remains unchanged because the code returns a Find object in the RANGE object (the Content property returns a RANGE object).

WITH ACTIVEDOCUMENT. Content. Find

.Clearformatting

.Font. Bold = true.

With .replacement

.Clearformatting

.Font. Bold = false

End with

= "" "", ReplaceWith: = ", Format: = true, replace: = WDREPLACEAll

End with

Use Table, Column, Row, and Cell objects

The Word object model contains a table object, as well as objects of various elements in the table. You can use the table property with the Document object, the Range object, and the Selection object to return to the table collection. Table (Index) returns a separate Table object where Index is the index number of the table. The index number represents the location of the table in the selected content, range, or document. The following example converts the first table in the selected content to text.

IF selection. Count> = 1 THEN

Selection. Tables (1). ConvertTotext Separetor: = WDSEParateByTabsend IF

You can return a Cells collection with the Column object, the Range object, the ROW object, or the Selection object. Users can get a Cell object by using the Cell method of the Table object or the index cells collection. The following two statements can set mycell as a Cell object, which represents the first cell of the form of the active document.

Set mycell = activedocument. Tables (1). Cell (Row: = 1, Column: = 1)

Set mycell = activeDocument. Tables (1). Column (1). Cells (1)

Note To insert text in a cell in a table, you can use the text property, the InsertAfter method, or the INSERTBEFORE method with the RANGE object. You can return a RANGE object with the Cell object using the RANGE attribute. The following example is inserted into a continuous cell sequence in each of the cells of the table.

i = 1

For Each C in ActiveDocument. Tables (1). Range. Cells

c. ing. Insertbefore text: = "Cell" & i

i = i 1

Next C

You can return Column attributes with a table object, a Range object, or a Selection object. Columns (Index) returns a separate column object where Index is the index number. The following example selects the first column of the table.

ActiveDocument. Tables (1). Column (1). SELECT

You can use the ROW property with the Table object, the Range object, or Selection object to use the ROW property to return the ROWS collection. Rows (INDEX) returns a separate ROW object where Index is the index number. The following example adds a top grain to the first line of the table.

ActiveDocument. Tables (1). Rows (1). Shading. Texture = WDTEXTURE10PERCENT

Modify the row and columns of graphics tables

When the user tries to use in a graphic table (or any table, there are two adjacent cells being merged, but the row and columns are not unified), a runtime error may occur. . If each column of the first table in the active document contains inconsistent line numbers, the following examples will be wrong.

ActiveDocument. Tables (1). Rows (1). Borders.enable = false

Users can first use the SelectColumn or Selectrow method to select a particular row or column, to avoid such errors. When the user selects a row or column, use the Cells property with the Selection object. The following example selected the first line of the table one of the active documentation. This example returns the selected cell (all cells in the first row) in the first row to delete the border.

If ActiveDocument. Tables (1). Uniform = false

ActiveDocument. Tables (1). Cell (1, 1). SELECT

WITH SELECTION

.Selectrow

.Cells. Borders. Enable = false

End with

END IF

The following example selected the first column of the table. This example uses a For Each ... Next loop to add text to each of the cells in the selected content (all cells in the first column).

If ActiveDocument. Tables (1). Uniform = false

ActiveDocument. Tables (1). Cell (1, 1). SelectSelection. SELECTCOLUMN

i = 1

For Each Ocell in Selection. Cells

Ocell.range. Text = "Cell" & i

i = i 1

Next Ocell

END IF

Use other ordinary objects

This section provides information and techniques for using some normal Word objects.

Use the Headerfooter object

The HeaderFooter object can represent one header or a footer. The HeaderFooter object is a member of the Headerfooter collection, which can be used in the section object. Headers (index) or footer (index) property returns a separate HeaderFooter object where Index is a value of WDHeaderfooterIndex constants.

The following example creates a RANGE object (ARANGE) that represents the main footer of the first section of the Activity Document. After this example sets the RANGE object, it deletes existing footprints. It also adds the Author domain and two tables and FileName domains to the foot.

SET Orange = ActiveDocument. Sections (1). Footers (WdheaderfooterPrimary). Range

With Orange

. Delete

= Orange, Type: = WDFIELDFILENAME, TEXT: = "/ P"

.Insertafter text: = VBTAB

.Insertafter text: = VBTAB

.COLLLAPSE DIRECTION: = WDCOLLAPSSTART

.Fields.add range: = Orange, Type: = WDFIELDAUTHOR

End with

Note PagenumBers collection can only be used in the HeaderFooter object. You can apply the Add method to the PAGENUMBERS collection to add a page number to a header or footer.

Use styles collection

Styles collection can be used in the Document object. The following example changes the format of the "Title 1" style in the activity document.

ActiveDocument. Styles (WDStyleHeading1). Font. Name = "arial"

Styles collection cannot be used in the Template object. If you want to modify the style in a template, you can use the OpenASDocument method to open the template as a document so that the user can modify the style. The following example changes the format of the "Title 1" style in the template attached to the activity document.

Set adoc = ActiveDocument. AttachedTemplate. OpenASDocument

With adoc

.Styles (WDStyleHeading1). Font. Name = "arial"

.Close savechanges: = WDSAVECHANGES

End with

Commandbars

You can use the CustomizationContext property using the CustomizationContext property before using the COMMANDBARS collection (representing the menu bar and toolbar). The following example adds the "Double Underline" command to the "Format" toolbar. Because custom changes are saved in the Normal template, all documents will be affected.

CustomizationContext = NORMALTEMPLATE

Commandbars ("formatting"). Controls. Add type: = msoControlButton, _ID: = 60, before: = 7

To learn more about the scope of the menu bar and toolbar, see Chapter 8, "Menu Bar and Toolbar".

Use Dialogs collection

You can use the Dialogs property to return Dialogs collection, which represents the Built-in Word dialog (eg, "Open" and "Save" dialog, etc.). Users cannot create a new built-in dialog or add a built-in dialog to the Dialogs collection. To learn about the content that creates a custom dialog with ActiveX controls, see Chapter 12, ActiveX Controls, and Dialogs.

Return to MailMerge and MailMerge objects

You can use the MailMerge property of the Document object to return a MailMerge object. Regardless of whether or not the specified document is a mail merge document, you can use the MailMerge property. Before the user performs the merge with the Execute method, you can use the State property to determine the status of the message merge operation. If the active document is the primary document of the data source, the following example will perform a mail merge.

Set mymerge = activeDocument.mailmerge

IF mymerge. State = wdmainanddatasource the mymerge. EXECUTE

Envelope properties using the Document object can return an envelope object. ENVELOPE objects can be used regardless of whether the user adds an envelope to the designated document. However, if the user uses the following attributes without adding an envelope to the document: address properties, addressFromLes, addressFromtop properties, feedsource properties, returnaddress properties, returnaddressFromlet properties, returnaddressFromtop properties, or UpdaddIcument properties.

The following example uses the ON ERROR GOTO statement to capture the user who does not add an envelope to the active document. However, if the user has added an envelope to the document, the recipient address will be displayed.

ON Error Goto Errorhandler

Msgbox ActiveDocument. Ready. Address

Errorhandler:

IF ERR = 5852 Then Msgbox "envelope is not in the specified document"

Add and edit the domain in the document

The user can add a domain to the document by applying the Add method to the Field collection. The following example adds a DATE domain to replace the selected content.

ActiVedocument. Fields. Add range: = Selection. Range, TYPE: = WDFIELDDATE

After adding a domain, users can return or set domain results and domain code by using the Result or Code property, both of which can return a RANGE object. The following example changes the first domain code of the selected content, update the domain, and display the domain results.

IF selection. Count> = 1 THEN

WITH SELECTION. Fields (1)

.Code. Text = "createDate / * mergeFormat"

.Update

Msgbox. Result. Text. Text.

End with

END IF

Comparison of InlineShape objects with shape objects

A Shape object represents an object of the graphical layer, such as a self-selected graphic, any polygon, an OLE object, an ActiveX control, a picture, and more. The SHAPE object is locked within the text, but can be moved anywhere, users can position them at any location of the page. To learn more about using Shape objects, see Chapter 10, "Shapes and Graphics", or see "Shape Object" in Help. An InlineHape object represents an object of the document text layer. An embedded shape may be a picture, an OLE object, or an ActiveX control. You can treat the InlineShape object as characters and put it like characters in a line of text. To learn more about the Inline, see "InlineShape Collection Object" or "InlineShape Object" in Help.

Use the Formfield object in the Word Form

Users can create a Word online form that contains check boxes, text text boxes, and drop-down list boxes. Use the Forms toolbar to insert these form elements. Corresponding Visual Basic objects are Checkbox, TextInput, and Dropdown. All of these objects can be used in any FormField object in the FormFields collection; however, users should use the corresponding objects using the type of field domain. For example, the following command selects a check box from the "Check1" domain of the active document.

ActiveDocument. Formfields ("Check1"). Checkbox. Value = true

In addition to the form elements in the Forms toolbar, users can also add an ActiveX control to a online form. Use the Control Toolbox to insert an ActiveX control. Users can insert the control into the text layer or graphics layer; the control will be represented by an InlineShape object or a shape object, respectively. To learn more about using the ActiveX control, see Chapter 12, "ActiveX Controls, and Dialog).

Determine whether the object is effective

You can determine whether the object returned by an expression or the object returned by a particular object or a variable referenced by the user code is valid, to avoid errors at runtime. This section discusses some techniques for checking the validity of the expiration return value or variable save value.

Users can use the TypenAme function with a variable or expression to determine the type of object. If Selection. NextField returns an Field object, the following examples will display a message in the status bar.

If TypeName (Selection. Nextfield) = "Field" Then statusbar = "A Field Was Found"

The following examples are equivalent to the above example; differences only there is an object variable (MyField) to save the return value of the NEXTFIELD method.

Set myfield = selection. Nextfield

If TypeName (Myfield) = "Field" Then Statusbar = "a Field Was Found"

If the specified variable or expression does not mean an object, it evaluates Nothing. If the nextfield method does not return Nothing (that is, if the nextfield method returns a field object, it is just another possible return value), then the following example will apply the UPDATE method to myfield.

Set myfield = selection. Nextfield

IF not (Myfield Is Nothing) Then Myfield. Update

Word contains shared isobjectValid properties. This property can be used to determine if an object referenced by a certain variable is valid. If the object referenced by the variable has been deleted, then the attribute returns false. The following example adds a table to the active document and assigns it to the variable ATABLE. This example removes the first table from the document. If the table referenced by the ATABLE is not the first table in the document (that is, if Atable is still a valid object), then this example deletes the border of the table. Set atable = activedocument. Tables. Add (Range: = Selection) Range, NumRows: = 2,

Numcolumns: = 3)

ActiveDocument. Tables (1) .delete

If isobjectvalid (atable) = true kil. Borders. Enable = false

Modify the word command

The user can modify the vast majority of Word commands by transitioning commands to macros. For example, the "Open" command in the File menu allows Word to display each file in the current folder, not only the Word document file list (in Windows, the file that is called .doc).

To display a list of built-in Word commands in the Mobs dialog (in the Tools menu), you can select the "Word Command" in the "Macro Location" column in the dialog. Each available menu, toolbar or shortcut command is listed in this dialog. Each menu command starts with the menu name associated with the command. For example, the "Save" command in the File menu is displayed as "FileSave".

The user can replace a Word command with a macro by giving the macro and the word command. For example, if the user creates a macro called "FileSave", when the user: In the File menu, click Save in the "Save" toolbar or click FileSave specified in the "Frequent" toolbar. When shortcuts, Word will run the macro.

Modify the word command

In the Tools menu, point to Macro with your mouse, then click Macro Location.

In the "Macro Location" column, click Word Command.

In the "Macro" column, select the word command to modify (for example, FileSave).

In the "Macro Location" column, select the position where you want to save the macro or the location of the document. For example, click Normal.dot to create a shared macro (the filesave command will automatically modify all documents).

Click Create.

The Visual Basic editor is opened, which shows a module that contains a new process with the same name as the command that is just selected. If the filesave command is selected, the FileSave macro appears, as shown in the following example.

SUB Filesave ()

Filesave Macro

SAVES The Active Document Or Template

Save the event document or template

ActiveDocument.save

End Sub

Users can add additional commands or delete existing ActiveDocument. Save commands. FileSave commands are executed by the FileSave macro when running each time. To restore the original filesave command, you need to change the name of the FileSave macro or delete it.

Note The user can also replace a Word command with a subroutine named "main" by creating code modules with the word command (for example, FileSave).

Use event

An event can be an operation that is identified by an object (for example, opening a document or exiting from an application), or an operation that can write code to respond. Both a user or a program code can cause the event to occur, and the event can also be caused by the system. The only event supported by Word is listed in the table below, which also lists the ActiveX control events, which will be discussed in Chapter 12 "ActiveX Controls and Dialogs". To learn about using Word events, see the following Help topic: "Events with Document Objects", "Events Using ActiveX Controls", and "Events using Application objects".

Document event

When a user opens or closes an existing document, or when the user has created a new document, the document event has occurred, as shown in the following example.

Event description

A Close event occurs when a document is turned off.

A new event occurs when you create a template-based new document.

Open event occurs when a document is turned on.

A document event process has a range depending on the location it saved. If the OPEN or Close event process is saved in one document, the process will only occur when the user turns off or opens the document; if the OPEN or Close event is saved in a template, the document based on the template is turned on or turned on or This process takes place when the template itself. A new event process must be saved in the template; a new event process saved in the document will never run because the document can only be created based on the template.

The following example expands the window of the Word application to the maximum when opening a document.

Private sub document_open ()

Application. WindowsTate = WDWindowStateMaximize

End Sub

ActiveX control event

Word executes LostFocus and GotFocus events for the ActiveX control in the Word document.

Event description

The LostFocus event occurs when the focus is removed by embedded ActiveX control.

When the focus is moved to the embedded ActiveX control, a GOTFOCUS event occurs.

The following example keeps CommandButton1 in disabled state until the user typed a value in TextBox1.

Private sub textbox1_lostfocus ()

If TextBox1. Value = "" "

CommandButton1. Enabled = false

Else

CommandButton1. Enabled = true

END IF

End Sub

Documents for other ActiveX control events are in the Microsoft Form Help. See Chapter 12, "ActiveX Controls and Dialogs) for content using the ActiveX control in the custom dialog and documentation.

Application event

APPLICATION events occur when the user exits the application or focus movement to another document. However, unlike the Document and ActiveX control events, the Application event default event is disabled. Before users use events with the Application object, you must create a new class module and declare an Application type object containing an event. Users can create a category module in the form of a class module command (insert menu) in the Visual Basic editor.

Enable events for Application objects, it is best to add the following declarations to class modules.

Public WitHevents App as Application

After defining a new object containing an event, it will appear in the Object drop-down list box of class modules, and then write event procedures for new objects. (After selecting a new object in the Object box, its valid event will appear in the "Process" drop-down list box.)

But before the process is run, you must connect the name objects in the class module to the Application object. To complete the above tasks, you can use the following declarations in any module ("EventClass" here is the name of the class module created by the user). Public x ask EventClass

When the user has created an X object variable (an instance of the EventClass class), the app object of the enventClass class can be set to the Word Application object equivalent.

Sub initializeapp ()

SET X. APP = Application

End Sub

After the user runs the initializeApp process, the App object in the EventClass class module points to the Word Application object, and as long as the event occurs, the event process in the class module will run.

After the user disables the event of the Application object, the event procedure can be created for the events in the following table.

Event description

When a new document is created, open an existing document or make another document becomes an active documentation.

The QUIT event happens when the user exits WORD.

The following instance ensures that the "Common" toolbar and "format" toolbar are visible before the user exits Word. As a result, these toolbars will not appear when the Word is restarted.

Private sub App_quit ()

Commandbars ("standard"). Visible = true

Commandbars ("Formatting"). Visible = TRUE

End Sub

Use automatic macro

By giving a special name to a macro, the user can automatically run it when performing operations such as starting Word or open a document. Word identifies the following name as an automatic macro, or "automatic" macro.

Macro

Run

Autoexec

Each time you start Word or load a global template

Autovew

Each time you create a new document

Autoopen

Every time you open an existing document

AutoClose

Turn off a document each time

AutoExit

Each time you quit Word or uninstall a global template

For more information on using an automatic macro, see "Automatic Macro" in Help.

Use automation

In addition to Word data, users may also want their application to exchange data with other applications, such as Microsoft Excel, Microsoft PowerPoint, or Microsoft Access. Users can communicate with other applications by using automation (previous OLE automation).

Automate Word from another application

Automated Run Users return, edit, and output data by reference to objects, properties, and methods of another application. Users can use the Application object referenced in another application called an automation object. The first step that Word can be used by another application is to create a reference to the Word Type Library. To create a reference to the Word type library, you can click "Reference" in the Tools menu in the Visual Basic Editor, then hook it in the check box next to Microsoft Word 8.0 Object Library.

Next, declare an object variable that references the Word Application object, as shown in the following example.

DIM Appwd as Word. Application. 8

With the Visual Basic CreateObject function or getObject function with the Word OLE program identifier, as shown in the following example. If you want to see the Word time, set the Visible property to True.

DIM Appwd as Word. Application. 8

Set appwd = createObject ("word. Application.8") appwd. Visible = TRUE

The CreateObject function returns a Word Application object and assigns it to the appwd. By using the object, attributes, and methods of the Word Application object, the user can control Word with this variable. The following instances create a new Word document.

Appww. Documents. Add

The CreateObject function starts a Word time period when references the object variable of the Application object, which is not turned off. Setting the object reference nothing keyword does not close Word. Instead, use the Quit method to close Word. The following Microsoft Excel examples insert the data of the "Worksheet 1" in the A1: B10 cells into a Word new document, and then adjust the data in the table. If the CreateObject function is used, this example uses the Quit method to close the new instance of Word. If the getObject function returns an error 429, then this example uses createObject to launch a new Word instance.

DIM Appwd as Word. Application

Err.Number = 0

ON Error Goto Notloaded

Set appwd = getObject (, "word. Application.8")

NOTLOADED:

IF err. Number = 429 THEN

Set appwd = creteObject ("word. Application.8")

Theerror = Err. Number

END IF

appwd. Visible = TRUE

WITH APPWD

Set mydoc = .documents. add

WITH .SELECTION

For Each C in Worksheets ("Sheet1"). Range ("A1: B10")

.Insertafter text: = C.Value

Count = count 1

IF country mod 2 = 0 THEN

.Insertafter text: = VBCR

Else

.Insertafter text: = VBTAB

END IF

Next C

CONVERTTOTABLE SEPARATOR: = WDSEParateByTabs

.Tables (1). Autoformat Format: = WDTABLORMATCLASSIC1

End with

MYDOC. saveas filename: = "c: / temp.doc"

End with

If Theerror = 429 Then Appwd. Quit

Set appwd = Nothing

Automate another application from Word

To switch data from Word and another application, you must first set a reference to another application class library in the Reference dialog (in the Tools menu). After this, another application object, attribute, and method will appear in the Object Browser and check the syntax automatically when compiling. Users can also get content sensitive helps for these objects, properties, and methods.

Next, declare an object variable that references a specific type of object in another application. The following example declares a variable that points to the Microsoft Excel Application object.

DIM Xlobj as Excel.Application.8

Users can get an Automation object by using the CreateObject or getObject function. The user can then add, change, or delete information by using another application object, attribute, and method. Close the application when the user completes the changes. The following Word example determines if the Microsoft Excel is running. If the specified Microsoft Excel task exists, this example uses a getObject function; otherwise, it uses the CreateObject function. This example then transmits the selected text to the A1 cell of "Worksheet 1" in the Microsoft Excel workbook. After the task is completed, use a set statement with the Nothing keyword to clear the Automation object variable. DIM Xlobj as Excel. Application. 8

If Tasks.exists ("Microsoft Excel") = True Then

Set Xlobj = getObject (, "Excel. Application. 8")

Else

Set Xlobj = CreateObject ("Excel. Application. 8")

END IF

Xlobj. Visible = TRUE

IF xlobj. Workbooks. Count = 0 Then Xlobj. Workbooks. Add

Xlobj. Worksheets ("sheet1"). Range ("a1"). Value = Selection. Text

Set Xlobj = Nothing

The following Word example determines if the PowerPoint is running. If there is a PowerPoint task, then this example uses a getObject function; otherwise it uses the CreateObject function. This example then creates a new presentation, the first text box of the document contains the name of the active Word document, the second text box contains the text of the first paragraph of the active document. After the task is completed, use the set statement with the Nothing keyword to clear the Automation object variable.

Dim pptobj as powerpoint. Application.8

IF Tasks. EXISTS ("Microsoft PowerPoint") = true kil

Set Pptobj = getObject (, "PowerPoint. Application.8")

Else

Set pptobj = creteObject ("PowerPoint. Application.8")

END IF

pptobj. Visible = true

Set pPTPRES = PPTOBJ. Presentations. Add

SET Aslide = pptpres. Slides. Add (index: = 1, layout: = pplayouttext)

Aslide. Shapes (1). TextFrame. TextRange. Text = ActiveDocument.name

Aslide. Shapes (2). TextFrame. TextRange. Text = ActiveDocument.Paragraphs (1). Range. Text

Set pptobj = Nothing

To learn about information about Microsoft Access, see Chapter 3, "Microsoft Access Object". To learn about the use of Data Access objects (DAOs), see "Using DAO" in Microsoft Word "in" Help ". Communicate with embedded Word objects

You can use any Word object's Application property to return to Word Application objects. This helps the Word Application object from the Word document embedded in another application. The following examples run in Microsoft Excel, set an object variable to the Word Application object. (In order to enable this example to operate, the shape in the active worksheet must be an embedded Word document.) The last command in this example adds text to the beginning of the Word document.

DIM Appwrd As Word. Application

Set EmbeddedDoc = ActiveSheet. Shapes (1)

Set appwrd = Embeddedddoc. OLEFORMAT. Object. Object. Application

AppWrd. ActiveDocument. Range (start: = 0, end: = 0). Insertbefore text: = "new text"

The following example is run in PowerPoint, set an object variable to the Word Application object. (In order to enable this example to run, the slide one must be an embedded Word document in a presentation.) The last command of this example shows the text in the Word document.

DIM Appwrd As Word. Application

SET EmbeddedDoc = presentations (1). Slides (1). Shapes (1)

Embeddeddoc. oleformat. Activate

Set appwrd = Embeddeddoc.oleFormat. Object. Application

MsgBox Appwrd. ActiveDocument. Content.Text

转载请注明原文地址:https://www.9cbs.com/read-3811.html

New Post(0)