Use range object to process Word Document Content

Source: Internet
Author: User
Tags printable characters
In all office applications Program Microsoft Word may be the most widely used application, and it often plays an important role in custom office solutions. Developers use word in different ways. Some methods are simple, while others are extremely complicated. Regardless of the custom solution involved, the basic methods for processing Word documents with Visual Basic for Applications (VBA) are the same. Below, I will give a general introduction to how to use Word and provide details about how to use the range object to process the content of the Word document. In word, almost all operations call the document object itself or its content. When you use VBA to operate word, the document object represents an open document, and all document objects are members of the documents set of the Application object. A document is a collection of characters, words, sentences, and paragraphs. It consists of characters, words, sentences, and paragraphs. Therefore, each document object has four sets: characters, words, sentences, and paragraghs. In addition, each document has a sections set that contains one or more sections. Each section has a headersfooters set that contains the header and footer of the Section. Note: You can view the complete word object model in the Microsoft Office 2000 Developer Object Model Guide (English. In addition, you can use the Object Browser and Microsoft Word Visual Basic Reference help to learn details about a specific object, attribute, method, and event. When word is used through VBA, the document object is in the center. If you want to open a document or create a new document, you must create a new document object. Each opened or newly created document is added to the documents set. A document with focus is called an activity document, which is represented by the activedocument attribute. The document object is a member of the documents set. You can use the document object index value (location of the Document Object in the documents set, 1 is the first document in the set) or name to reference it. In addition, you can use the activedocument attribute to reference a document with focus. For example, if a document named policies.doc is a unique open document, the following three object variables will all point to policies.doc: dim docone as word. documentdim doctwo as word. documentdim docthree as word. documentset docone = documents (1) set doctwo = documents ("policies.doc") set docthree = activedocument generally, do not reference documents using the index values in the documents set, because when other documents are opened or closed, the index value of a specific document may change accordingly. Generally, you can use the activedocument attribute, the add method of the documents set, or the document object variable created by the open method. The following example shows how to use the activedocument attribute to add an address to a document with focus: 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, the following example shows how to instantiate the document object variable by using the open method of the documents set. Dim docpolicy as word. documentset docpolicy = documents. open ("C: \ My Documents ents \ policies.doc") the last example shows how to use the add method to create a document object instance for a new empty document. Dim docpolicy as word. documentset docpolicy = documents. Add a document opened by using the open method or a document created by using the add method will become the current active document represented by the activedocument attribute. If you want to make other documents in the documents set into activity documents, you can use the active method of the Document Object. Once you obtain the document object to be operated, most of the work you want to perform through VBA will involve text operations. First, you must specify a part of the document and perform some operations on it. For example, add or delete text, or set the word or character format. You can use the range or selection objects to do a lot of work. In this month's column, I will only discuss the range object. Next month, we will further discuss the specific content of the selection object. Understanding paragraph markup of word when you process text through a program, you must understand how word processes paragraph markup. Fundamentally speaking, Word documents are just a huge NLP stream. People tend to think that documents are a collection of words, sentences, and paragraphs. But in fact, the document is a few characters. Each character has a certain effect. Some characters are letters, spaces, or tabs, and others are paragraph marks or pagination characters. Paragraph tags play unique roles in Word documents. Sometimes such roles are easy to misunderstand. A paragraph contains a paragraph mark and all text (excluding the previous paragraph mark) between the paragraph mark and the previous paragraph mark ). In addition, it is important that the Section tag contains all the format information of the paragraph. When you copy words, sentences, and paragraphs, if you include a paragraph tag, all format information contained in the paragraph tag is also copied and applied to the section when they are pasted elsewhere. If you want to copy text from a paragraph and paste it into another paragraph, but do not want to copy the paragraph format at the same time, do not include the paragraph mark next to the text you want to copy. Each blank word document has only one paragraph tag, which simultaneously contains the character object, word object, sentence object, and Paragragh object. However, the "Statistics" tab in the "properties" dialog box ("file" menu) shows that there are no characters, words, sentences, and paragraphs in the report blank document. This difference highlights an important aspect of word. When you program these objects, you need to pay special attention to this. The range object indicates a continuous range in the document, which is defined by a starting character position and a ending character position. This continuous range can be as small as an insert point and as large as the entire document. It may also be (rather than must be) the range expressed by the current section. You can also define a range object to indicate a range different from that of the current section. You can also define multiple range objects in the same document. A range object contains non-printable characters, such as spaces, carriage returns, and paragraph tags. A typical method to create a range object using a range object is to declare an object variable of the range type, and then use the range method of the Document Object or another object (such as character, word, sentence, or selection object) to instantiate the variable. For example Code Two range objects are created, indicating the second sentence in the activity document. Dim rngrangemethod as word. rangedim rngrangeproperty as word. rangewith activedocument if. sentences. count> = 2 then set rngrangemethod =. range (. sentences (2 ). start ,_. sentences (2 ). end) set rngrangeproperty =. sentences (2) end ifend with when you use the range method to specify a specific range of documents, you must use the start parameter of this method to specify the start position of this range, use the end parameter to specify the end position. The first character of the document is 0. The position of the last character is equal to the total number of characters in the document. You can use the Count attribute of the characters set to determine the number of characters in the document. As shown in the preceding example, you can also use the start and end attributes of the bookmark, selection, or range object to specify the start and end parameters of the range method. You can set the start and end parameters to the same number, which creates a range that does not contain any characters. You can use the setrange method of the object to set or redefine the content of the range object. You can also specify or redefine the start position of a range by using the start attribute of the range object or the movestart method. Similarly, you can use the end attribute of the range object or its moveend method to specify or redefine the end position of the range object. The following example uses the contentragne object, which contains all the content of the document. Then, change the endsetrange method to redefine the range so that it contains the first section of the document. Finally, use the moveend method to extend the end position of the range to the end of the second section of the document. In this example, each step prints the number of characters in the current range to the "immediate window ". Sub rangeexample () dim rngsample as range set rngsample = activedocument. content with rngsample Debug. Print "the range currently contains" &. characters. Count _ & "characters. ". End = activedocument. Sentences (1). End Debug. Print" contains "&. characters. Count _ &" characters. ". Setrange start: = 0, end: = activedocument. _ Paragraphs (1 ). range. end debug. print "the range is now included "&. characters. count _ & "characters. ". Moveend unit: = wdparagraph, Count: = 1 Debug. Print" the range currently contains "&. characters. Count _ &" characters. "End withend sub you can also use the Find Attribute of the object to return the find object and redefine the range object. The following example shows how to use the find attribute to locate the text in the activity document. If the text is found, the range object is automatically redefined to include text that meets the search criteria. With rngrangetext. Find. clearformatting if. Execute (findtext: = "Find me! ") Then' rngrangetext is redefined. End ifend with many word objects have the range attribute that can return the range object. You can use the range attribute of an object to return the range object if you need to use the attributes and methods of the range object, but the object itself does not provide these attributes and methods. For example, the following code uses the range attribute of the Paragragh object to return the range object and sets the text format in the first section of the document: dim rngpara as rangeset rngpara = activedocument. paragraphs (1 ). rangewith rngpara. bold = true. paragraphformat. alignment = wdalignparagraphcenter. font. after name = "Arial" end with defines the range object, you can apply the methods and attributes of this object to modify the content of the specified range or obtain relevant information. For example, you can use the storytype attribute of the range object to determine the position of the range in the document. You can use the text attribute of the range object to specify or determine the text contained in the range object. For example, the following code first displays the text in the range object, then changes the text, displays the new text, and finally restores it to the original text. This example shows how to use the range property of a range object to copy and paste text to a document without changing the structure of the original paragraph. Note how to replace the section mark included in the selected original section with the new text containing the section mark (vbcrlf) in the strnewtext variable. Public sub changetextsample () dim rngtext as range dim stroriginaltext as string dim strnewtext 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 restored. "End withend sub you can use the storytype attribute of the range object to determine the position of the range in the document. A document consists of a specific range of documents that contain text. A document can contain up to 11 types of documents, which indicate different scopes such as body, header, footer, and annotation. You can use the storyranges attribute to return the storyranges set. The storyranges set contains a range object, indicating the components of each document in the document. The New Word document contains only one document component, called "main text", which indicates the text of the document body. Even a blank document contains one character, one word, one sentence, and one paragraph. You do not need to add the new document components to the document. When you add text to a certain part of a document (one of 11 document components), word automatically adds them. For example, if you want to add a footer, word adds the footnotes document component. If you want to add an annotation, word adds the components of the comments document to the storyranges set of the document. You can use the range property to return a range object to represent the components of each document in the document. For example, the following code prints the text related to the main text and comments documents: dim rngmaintext as word. rangedim rngcommentstext as word. rangeset rngmaintext = activedocument. storyranges (wdmaintextstory) set rngcomments = activedocument. storyranges (wdcommentsstory) debug. print rngmaintext. textdebug. print rngcomments. text uses the insertbefore or insertafter method of the range object to add text to an existing range object. In fact, there is a whole type of method, whose name starts with "insert" and can be used to operate a range object. If there is a process that can combine the insertbefore and insertafter methods of the range object with the text attribute, it will be very useful. This process can be used to process a large amount of work in the same place during programming and processing of text. The inserttextinrange shown below is such a process. You can call the inserttextinrange process whenever you need to add text to the range object. In other words, this process is useful whenever you need to programmatically change existing text in the Word document. The inserttextinrange process uses two necessary variables and an optional variable. The strnewtext variable contains the text you want to add to the range object, which is specified in the rngrange variable. The optional intinsertmode variable specifies how to add new text to a range. The variable value is one of the three custom enumeration constants, specifying whether to use the insertbefore method, insertafter method, or text attribute to replace the existing range text. Public Enum opgtextinsertmode before after replaceend enumfunction inserttextinrange (strnewtext as string, _ optional rngrange as word. range, _ optional intinsertmode as opgtextinsertmode = _ replace) as Boolean this process inserts the specified text of the strnewtext parameter into the range object specified by 'rngrange. It calls the 'islastcharparagraph process to clear the subsequent paragraph mark from the rngrange object. Call islastcharparagraph (rngrange, true) with rngrange select case intinsertmode case 0' insert text before the range.. Insertbefore strnewtext case 1 'inserts text after the range.. Insertafter strnewtext case 2 'replaces the text in the range.. Text = strnewtext case else end select inserttextinrange = true end withend function note that before inserting text in the range, the islastcharparagraph process is used to delete the paragraph mark of the last paragraph. The following example uses the CHR $ () function to mark a paragraph with character code 13. Function islastcharparagraph (byref rngtextrange as word. Range, _ optional blntrimparamark as Boolean = false) as Boolean 'this process accepts the character, word, sentence, or paragraph range' as the first parameter. If the last character in the range is a paragraph mark, true is returned; otherwise, false is returned. 'This process also accepts a Boolean parameter to specify whether to delete the text when there is a paragraph mark at the end. 'When the blntrimparamark parameter is true, this 'process calls 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 response = true if not blntrimparamark = true then exit function else do rngtextrange. setrange rngtextrange. start, _ rngtextrange. start + _ rngtextrange. characters. count-1 call islastcharparagraph (rngtextrange, true) loop while in STR (rngtextrange. text, CHR $ (13) <> 0 end if end ifend function in this example, the Count attribute of the characters set of the range object is used to redefine the end point of the range object. For more information about paragraph processing, please note how to use the vbcrlf built-in constant in the text in the strnewtext variable to create a paragraph mark at the end of the text during the changetextsample process discussed earlier, to replace the existing text in section 1st of the activity document. This is done to prevent the new document from being part of the second paragraph. When you create a range object that represents a character, word, or sentence object and the object is located at the end of a paragraph, the paragraph mark is automatically included in the range. In addition, the range object will contain subsequent empty section tags. For example, in a document composed of two paragraphs, assume that the first paragraph contains three sentences, and the second paragraph is empty, the range object created in the following code indicates the last sentence in the first section: Set rngcurrentsentence = activedocument. sentences (3) because the rngcurrentsentence range object references the last sentence of the first paragraph, the paragraph mark (and all subsequent blank paragraph marks) of the paragraph will be automatically included in the range. If you apply the text attribute of this object to a text string that does not end with a paragraph mark, the second paragraph in the document will be deleted. When you write in a Word document Composition When you use this VBA code, you need to process the section tags that appear in the text. When you cut or paste text in the range object, you can use two basic methods to process the paragraph MARK: In the text to insert a document, contains a new paragraph mark (expressed by vbcrlf constant), as shown in the changetextsample process. Exclude the last paragraph mark from the range object, as shown in the application of the islastcharparagraph function during the inserttextinrange process.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.