In all Office applications, Microsoft Word may be the most widely applying application, which often plays an important role in a custom Office solution. Developers use Word in a variety of different ways, and some ways are very simple, while others are extremely complex. Regardless of the custom solution involved, the basic method of processing the Word document with Visual Basic for Applications (VBA) is the same.
Understand basic method
In Word, almost all operations should call the Document object itself or their content. When you use the VBA operating Word, the Document object represents an open document, and all Document objects are members of the Documents collection of Application objects.
The document is a collection consisting of characters, words, sentences, and paragraphs, characters composition words, word composition sentences, sentence composition paragraphs, and so on. Therefore, each Document object has four collection of CHARACTERS, WORDS, SENTENCES, and ParagraGHS. In addition, each document has a sections collection that contains one or more segments, each section has a Headersfooters collection that contains this section and footer.
Note: You can check the full Word object model in Microsoft Office 2000 Developer Object Model Guide (English). Alternatively, you can also use object browsers and Microsoft Word Visual Basic reference help to learn more about specific objects, properties, methods, and events.
The Document object is in a central location when using Word using Word. If you want to open a document or create a new document, create a new Document object. Each open or newly created document is added to the Documents collection. A document with focus is called an active document, represented by the ActiveDocument property.
Document objects as a member in the Documents collection, you can reference it by using the index value of the Document object (Document object in the Documents collection location, 1 is the first document in the collection) or name. Alternatively, you can use the ActiveDocument property to reference the currently focus document. For example, if the document named policies.doc is the only open document, the following three object variables will all point to Policies.Doc:
Dim docone as word.document
DIM DOCTWO AS WORD.Document
Dim DOCTHREE AS WORD.DOCUMENT
Set docone = Documents (1)
Set doctwo = Documents ("policies.doc")
SET DOCTHREE = ActiveDocument
In general, do not use the index value in the Documents collection to reference the document, because when other documents are turned on or off, the index value of a particular document may change. Typically, you can use the ActiveDocument property or use the Document object variable created using the Documents collection or Open method. The following example shows how to add an address to the current focus document using the ActiveDocument property:
With activedocument
.Envelope.insert address: = "office talk" _
& vbcrlf & "
One Microsoft Way "& Vbcrlf _
"
Redmond
,
WA
98052
", Returnaddress: = _
"David Shank" & VBCRLF & _
"77
First street
& vbcrlf & _
Any Town,
USA
12345 "
End with
The following example illustrates how to instantiate the Document object variable by using the open method of the Documents collection.
DIM DOCPOLICY As Word.Document
SET DOCPOLICY = Documents.Open ("c: / my documents / policies.doc")
The last example shows how to create an instance of the Document object for the new empty document by using the Add method.
DIM DOCPOLICY As Word.Document
SET DOCPOLICY = Documents.Add
By using the document opened using the Open method, or by using the document created using the Add method, it will become the current active document represented by the ActiveDocument property. If you want to make other documents in the Documents collection to become an active document, you can use the Document object's Active method.
Once you get the Document object to be operated, most of you want to work through VBA will involve the operation of text. First, you want to specify a portion of the document and then perform some operations. For example, add or delete text or set a word or character. You can use the two objects of Range or Selection to do a lot of work. In this month's column, I will only discuss the Range object. We will further discuss the specific content of the Selection object next month.
Understanding Word's paragraph tag
When you process text through the program, you must understand how Word handles paragraph tags. Fundamentally, the Word document is just a huge character stream. People tend to think that the document is a collection of words, sentences, and paragraphs. But in fact, the document is some characters. Each character has a certain role. Some characters are letters, spaces, or tabs, and other characters are paragraph tags or pagins.
Paragraph tag played a unique role in the Word document, sometimes this role is easily misunderstood. The paragraph contains a paragraph mark and all texts between this paragraph tag and the previous paragraph tag (excluding the previous paragraph tag). In addition, it is important that the paragraph marks all the format information of this paragraph.
When copying words, sentences, and paragraphs, if the paragraph tag is included, all format information contained in the paragraph tag is also copied and applied to the segment of the segment when they are pasted into other locations.
If you want to copy text from the paragraph and paste it into another paragraph, do not want to copy the paragraph format simultaneously, please include the paragraph tag next to the text you want to copy.
Each blank Word document has only one paragraph tag, which contains both the Character object, Word object, the Sentence object, and Paragragh object. However, the "Properties" dialog ("File" tab in the File menu reports no characters, words, sentences, and paragraphs in the blank document. This difference highlights an important side of Word. When programming these objects, you need to pay special attention to this.
Range object
The RANGE object represents a continuous range in the document, defined by a start character position and a termination character location. This continuous range can be small to an insertion point, large to the entire document. It may also be (rather than necessarily) by the current section. You can also define a range object, representation, and different ranges. Multiple RANGE objects can also be defined in the same document. The characters in the Range object include non-print characters, such as spaces, carriage return, and paragraph tags. Use the RANGE object
A typical way to create a RANGE object is to declare an object variable of a Range type, and then instantiate the variable with the range method of the Document object or another object (for example, CHARACTER, WORD, SENTENCE, or SELECTION object). For example, the following code creates two RANGE objects that represent the second sentence in the movable document.
Dim RNGRANGEMETHOD AS WORD.
Dim RNGRANGEPROPERTY AS WORD.RANGE
With activedocument
If.sentes.count> = 2 THEN
Set rngrangemethod = .range (.sentes (2) .start, _
. Sentences (2) .end)
Set rngrangeproperty = .sentences (2)
END IF
End with
When you use the RANGE method to specify a specific range of the document, you must use the start parameter of this method to specify the position started by this range and use the END parameter to specify the end. The character position of the first character of the document is 0. The position of the last character and the total number of characters of the document are equal. You can determine the number of characters in the document by using the count attribute using the Characters collection. As shown in the example, you can also specify the start and end parameters of the RANGE method using the start and end properties of the Bookmark, Selection, or Range objects. You can set the start and End parameters to the same number, which will create a range that does not contain any characters.
You can use the object's setRANGE method to set up or redefine the contents of the Range object. You can also use the start attribute of the RANGE object or the location where the MoveStart method is specified or redefined. Similarly, you can also use the END attribute of the RANGE object or the location of the end of the range or redefine the range of the range.
The following example first uses the Contentragne object, which contains all the contents of the document. Then, change the endsetRange method to redefine the range so that the first paragraph of the document. Finally, use the MOveEnd method to extend the end position of the range to the end of the second paragraph of the document. Each step in this example prints the number of characters contained in the current range to "Immediate Window".
Sub Rangeexample ()
DIM RNGSAMPLE AS RANGE
Set rngsample = activeDocument.content
With RNGSAMPLE
Debug.print "Scope now contains" & .characters.count _
& "A character."
.End = activeDocument.sentences (1).
Debug.print "Scope now contains" & .characters.count _
& "A character."
.SetRange start: = 0, end: = activedocument._
Paragraphs (1) .range.end
Debug.print "Scope now contains" & .characters.count _
& "A character."
.Movend unit: = wdparagraph, count: = 1
Debug.print "Scope now contains" & .characters.count _
& "A character."
End with
End Sub
You can also redefine the RANGE object by returning a Find object by using the object's Find property. The following example demonstrates the location of the text in the active document with the FIND attribute. If the text is found, the Range object will automatically redefine with text that meets the search criteria.
With RNGRANGRANGETEXT.FIND
.Clearformatting
IF .Execute (FindText: = "Find ME!") THEN
'RNGRANGETEXT is redefined.
END IF
End with
Many Word objects have a range property that returns a RANGE object. In the case where you need to use the property and method of the RANGE object, the object itself does not provide these properties and methods, you can use the object's Range property to return to the RANGE object. For example, the following code returns a RANGE object using the RANGE property of the Paragragh object, thereby setting the format of the text in the document in the first paragraph:
DIM RNGPARA AS RANGE
SET RNGPARA = ActiveDocument.Paragraphs (1) .RANGE
With RNGPARA
.Bold = true
.Paragraphformat.Alignment = WDALIGNPARAGRAPHCENTER
.Font.name = "arial"
End with
Once the Range object is defined, you can apply this object's method and attribute to modify the contents of the specified range or get information. For example, you can use the StoryTyPE property of the Range object to determine the location of the Range in the document.
Handling text in the RANGE object
You can use the TEXT property of the RANGE object to specify or determine the text containing the range. For example, the following code first displays text in the RANGE object, then change the text and displays new text, and finally restores as original text. This example illustrates how to use the RANGE property of the RANGE object to copy text and paste into the document and maintain the original paragraph structure. Note How to replace the paragraph tag that contains the paragraph tag (VBCRLF) in the STRNEWTEXT variable.
Public Sub ChangeTextSample ()
DIM RNGTEXT AS RANGE
DIM StroriginalText As String
DIM STRNEXT AS STRING
Strnewtext = "this text is replacing the Original" _
& "Text in The First Paragraph of The Active"
& "Document. this is all done using only the" _
& "Text Property of the Range Object!" & VBCRLF
Set rngtext = activeDocument.paragraphs (1) .range
With RNGText
Msgbox .text, vbokonly, "this is the original text."
StroriginalText = .text
.Text = strnewtext
Msgbox .text, vbokonly, "this is the new text" _
& "INSERTED in Paragraph 1."
.Text = StroriginalText
Msgbox "The Original Text Is Restore."
End with
End Sub
You can use the StoryType property of the Range object to determine where the range is in the document. The document component is a specific range containing the text in the document. In one document, you can have 11 documents, indicating different scope of the body, header, footer, and annotation. You can use the StoryRanges property to return the StoryRanges collection. The Storyranges collection contains the RANGE object, indicating that each document in the document is constituted.
The new Word document contains only one document component, called "main text", which represents the text of the document body part. Even if a blank document also contains characters, words, sentences, and paragraphs.
You don't need to add a new document composition to the document. When you add text to a part of the document (one of the 11 document components), Word will automatically add them. For example, if you want to add a footer, Word will add a FOOTNOTES document component. If you want to add a comment, Word will add the Comments document component to the StoryRanges collection of the document.
You can use the Range property to return the RANGE object to represent each document in the document. For example, the following code prints the text related to Main Text and Comments documents:
DIM RNGMAINTEXT AS WORD.RANGE
DIM RNGCommentsText As Word.Range
Set rngmaintext = ActiveDocument.StoryRanges (WDMAINTEXTSTORY)
Set rngcomments = ActiveDocument.storyRanges (WDCommentsSstory)
Debug.print RNGMAINTEXT.TEXT
Debug.print RNGComments.Text
The text can be added to an existing Range object using the InsertBefore or InsertAfter method of the RANGE object. In fact, there is a category method that begins with "Insert" and can be used to operate the RANGE object.
If there is a process, you can combine the INSERTBEFORE and INSERTAFTER methods of the RANGE object with text properties, then it will be very useful. When programming your text, you can use this process to handle a lot of work in the same place. The INSERTTEXTINRANGE shown below is this process. Whenever you need to add text to the RANGE object, you can call the InsertTextInrange process. In other words, this process will be very useful whenever you need to program the existing text in the Word document.
The INSERTTEXTINRANGE process uses two necessary variables and an optional variable. The STRNEWTEXT variable contains text you want to add to the Range object, which is specified in the RNGRANGE variable. The INTInsertMode optional variable specifies how new text is added to a range. The value of the variable is one of three custom enumerations, specifies whether to replace the existing range text using the INSERTBEFORE method, an InsertAfter method, or a Text property.
Public Enum OpgTextInsertModebefore
After
Replace
END ENUM
Function inserttextinrange (Strnewtext As String, _
Optional RNGRANGE AS WORD.RANGE, _
Optional intInsertMode as opgtextinsertmode = _
Replace) as boolean
'This process specifies the text insertion of the strnewtext parameter
'RNGRANGE specified in the RANGE object. It calls
'Islastcharparagraph process from RNGRANGE
'Object Clear subsequent paragraph tags.
Call islastcharparagraph (RNGRANGE, TRUE)
With RNGRANGE
SELECT CASE INTISERTMODE
Case 0 'is inserted into the text before the range.
.INSERTBEFORE STRNEWText
Case 1 'is inserted into the text after the range.
.Insertafter strnewtext
Case 2 'The text in the replacement range.
.Text = strnewtext
Case Else
End SELECT
INSERTTEXTINRANGE = TRUE
End with
END FUNCTION
Note that before inserting text in the range, use the islastcharparagramraph process to delete the paragraph tag of the last paragraph. The following example uses a CHR $ () function to represent the paragraph tag with character code 13.
Function islastcharparagraph (byref RNGTextRange as word.range, _
Optional blntrimparamark as boolean = false) as boolean
'This process accepts characters, words, sentences or paragraphs Range
'As the first parameter. If the last character in the range
'Is a paragraph tag, then returns true; otherwise returns false.
'This process also accepts a Boolean parameter for designation
'Whether it is deleted when the text is finally present.
'When the BLntrimparamark parameter is true, this
'Current call itself to delete all subsequent paragraph tags.
DIM STRLASTCHAR AS STRING
StrlastChar = Right $ (RNGTextRange.text, 1)
IF INSTR (Strlastchar, CHR $ (13)) = 0 THEN
Islastcharparagraph = false
EXIT FUNCTION
Else
Islastcharparagraph = TRUE
IF not blntrimparamark = true kil
EXIT FUNCTION
Else
DO
RNGTextRange.seTRANGE RNGTEXTRANGE.START, _
RNGTEXTRANGE.START _ _ _ _ _
RNGTEXTRANGE.CHARACTERS.COUNT - 1
Call islastcharparagraph (RNGTextRange, True)
Loop While INSTR (RNGTextRange.text, Chr $ (13)) <> 0
END IF
END IF
END FUNCTION
In this example, the COUNT property of the RANGE object's CHARACTERS collection is used to redefine the end point of the RANGE object.
More information about processing paragraphs
During the previously discussed ChangeXTSample process, please note how the text in the strnewtext variable uses the VBCRLF built-in constant to create a paragraph tag at the end of the text, thereby replacing the existing text in paragraph 1 of the active document. This is to avoid new documents into part of the second paragraph. When you create a RANGE object that represents a CHARACTER, WORD or SENTENCE object, and the object is located in the end position of the paragraph, the paragraph tag is automatically included in the range. Moreover, the RANGE object will contain subsequent empty segment marks. For example, in a document consisting of two paragraphs, assume that the first paragraph contains three sentences, and the second paragraph is empty, then the RANGE object created by the following code represents the last sentence in the first segment:
SET RNGCURRENTSENTENCE = ActiveDocument.Sentences (3)
Because the RNGCURRENTENTENCE RANGE object references the first sentence of the first paragraph, the paragraph tag (and all subsequent empty segment tags) will be automatically included in the range. If you follow the text attributes in this object to a text string that does not end the paragraph tag, the second paragraph in the document will be deleted.
When you write a VBA code for your text in the Word document, you need to process paragraph tags that appear in your text. When you cut or paste your text in the Range object, you can use two basic methods to process paragraph tags:
In the text to be inserted into the document, contain a new paragraph tag (represented with VBCRLF constant), as shown by the ChangeTextSample process.
Mark the last paragraph is excluded from the RANGE object, as shown in the application of the IslastCharParaGraph function during the InsertTextInrange process.