Word programming language. Creating applications in VBA for MS WORD


Formatting a Document

The most important feature of working with VBA in Word is inserting text into a document when working with applications. For this purpose, Range and Selection objects are used, which are the main ones for almost any operation that can be performed using Word VBA. Some of these actions can be applied to documents as a whole, but in general you need a range or selection before you make changes. We will, however, look at what you can do with the document when you create it.

Open document Word already contains Range objects that correspond to many of its elements. Each paragraph, table, table cell, comment, etc. defines ranges. For example, in order to insert some text into an existing document, you need to write the code:

ActiveDocument.Paragraphs(1).Range.Text = "Oxo-xo!!"

Moreover, this line will be located at the end of the existing paragraph. On the other hand, using the Selection object, you can also insert some text into the document by using the Add method and assigning the Text property to the Selection object:


Selection.Text = "Learning how to work with text in a Word document is important integral part programming skills in VBA, “+TextBox1.Text+”, and meets the needs of all programmers!”

As a result of this program code in the Word document the line will be displayed: “Learning how to work with text in a Word document is an important part of the ability to program in VBA, Svetlana, and meets the needs of all programmers!”

Description of procedures

Private Sub CommandButton1_Click()
If Documents.Count = 0 Then Documents.Add
Selection.Text = "When a current with a voltage of " + TextBox1.Text + "volts passes through a conductor with a length of " + TextBox4.Text + " meters, a cross-section of " + TextBox3.Text + " sq. mm and a resistivity of " + TextBox5.Text + " Ohm*mm^2/m for " + TextBox2.Text + " seconds will be highlighted " + TextBox6.Text + " heat joules"
Selection.Collapse direction:=wdCollapseEnd
End Sub

Private Sub CommandButton2_Click()
Unload Me
End Sub

Private Sub TextBox1_Change()
scet
End Sub

Private Sub TextBox2_Change()
scet
End Sub

Private Sub TextBox3_Change()
scet
End Sub

Private Sub TextBox4_Change()
scet
End Sub

Private Sub TextBox5_Change()
scet
End Sub

Private Sub scet()
If IsNumeric(TextBox1.Text) = True And
IsNumeric(TextBox2.Text) = True And
IsNumeric(TextBox3.Text) = True And
IsNumeric(TextBox4.Text) = True And
IsNumeric(TextBox5.Text) = True And Not Val(TextBox4.Text) = 0 And Not Val(TextBox5.Text) = 0 Then rez = ((Val(TextBox1.Text) ^ 2) * Val(TextBox2.Text) * Val(TextBox3.Text)) / (Val(TextBox4.Text) * Val(TextBox5.Text))
TextBox6.Text = Str$(rez)
CommandButton1.Enabled = True
Else
TextBox6.Text = ""
CommandButton1.Enabled = False
End If
End Sub

When working with text on the desktop Word sheet You need to know the following codes:

color definition
Selection.Font.Color =
wdColorRed – red
wdColorDarkRed – burgundy
wdColorDarkTeal – turquoise
wdColorBlue – blue
wdColorGreen – green
wdColorBlack – black
wdColorOrange – orange

determination of fat content
Selection.Font.Bold =
wdToggle – boldness

definition of style
Selection.Font.Italic=
wdToggle – italics

alignment definition
Selection.ParagraphFormat.Alignment=
wdAlignParagraphRight – right alignment
wdAlignParagraphCenter – center alignment
wdAlignParagraphJustify – left alignment

inserting a specific sentence into the text
Selection.TypeText Text:="Example of working with text"
inserting a new empty line
Selection.TypeParagraph
setting letter size
Selection.Font.Size = 14

One of the design elements of dialog boxes is the control element Image(drawing). Its main properties:

Autosize– changes the size of the picture on the form (automatically or not);

Picture– displays graphic file, displayed on the form;

pictureSizeMode – sets the scaling of the picture (not the entire picture, the entire surface of the object, entirely inside the object);

PictureAlignment– sets the location of the picture inside the object (left, right, top, bottom);
pictureTilling– covers an object with a mosaic from a drawing.

These properties are either set in the object properties window or specified in the listing.

Note . When working this application All input field values ​​must be numeric. VBA has a special function for checking whether the entered string is a number record or not - IsNumeric. To check if the values ​​in the last two input fields are non-zero, use the Val function, which converts a string expression into a numeric one if this string expression contains digits at the beginning (or everything consists of them).

The Str function does the opposite of what Val does - it converts numeric value expressions to a string, which allows this value to be further processed as a string.

Thus, the Val and Str functions convert the data types of the variables they process, from string to numeric and from numeric to string, respectively.

Create a button or panel in Word

You cannot assign a button or menu item to a form to directly call an application from Word - this can only be done for modules. Therefore, you need to use the following method. Create a macro (Menu + Insert + Module) in open project:

Subcounter()

userForm1.Show

EndSub

Rename this macro as you wish, such as Teplo. And execute the following actions:

1. Right-click anywhere on the toolbar.

2. From this menu, select the command Settings(or Service + Settings).

3. In the dialog box Settings click on the tab icon Teams.

4. Scroll the list Categories down and find the item Macros. Select this item. In the "Save in" list, select the name of your document in which the macro was created.

5. In the right window, find the required macro (or VBA program).

6. Drag the name of this macro or program to the toolbar.

7. Create a corresponding button label and, if necessary, a drawing (using right button mice).

8. Close the dialog box Setting, to complete the job.

9. As a result, a button to launch the application will be created.


Laboratory work №5


Related information.


Its properties and methods

Word.Document object, program work with document properties and methods in VBA

After we launched Word using the Application object, created (or opened, or found among already open ones) using the Documents collection - in general, we received a link to the document we need, we can perform work with this document various actions, implemented using the properties, methods and events of the Document object. This object has dozens of properties and methods, and here we will consider only the most important and frequently used ones. Obvious and rarely used properties will be left for independent consideration.

Note that the Document object can be accessed without creating a special object variable. There is also at least three ways to access the Document object:

  • work with a document as an element of the Documents collection. The request format may look, for example, like this: Documents.Item(1);
  • use special keyword ThisDocument. Using it you can get a link to the document object that owns the executable software module, For example:

MsgBox ThisDocument.Name

  • use the Application ActiveDocument object property. This property returns us the active document object:

MsgBox Application.ActiveDocument.Name

or simply

MsgBox ActiveDocument.Name

The most important properties of the Document object are presented below:

  • ActiveWritingStyle- current active style (heading of a certain level, plain text, hyperlink, etc.). It is recommended to check before entering text.
  • AttachedTemplate- the ability to connect a template (with all macros, styles, autotext entries, etc.) or check which template is connected (this can be done manually through the menu Service -> Templates and add-ons).
  • Background- returns a Shape object representing the background image (background images are only visible in Web document mode);
  • BuiltInDocumentProperties- the ability to get a link to the DocumentProperties collection with objects of the same name representing the built-in properties of the document (title, author, category, comments, etc.);
  • Characters- returns a collection of Range objects, each representing one character. Not only Document objects have this property, but also Selection and Range objects. Can be used, for example, to perform search and replace operations or statistical calculations (for example, if the translator is paid by the number of characters);
  • Content- a property that returns a Range object representing the main document story. To put it simply - just the text of the document, without headers, footers, comments, etc.
  • CustomDocumentsProperty- a property that returns a collection of DocumentProperties objects representing custom properties document. Can be used to save any variable values ​​along with the document. It is very convenient, for example, for counting the number of document openings, checkboxes printed/not printed, how many times a particular function was called, on which computers and by which user it was opened, etc.
  • DefaultTabStop- define the default indentation when using the tab character. The default is 35 points, which is approximately 1.25 cm;
  • DisableFeatures- disable features that only the latter understand Word versions(for compatibility with users who have older versions on their computers). Typically, the DisableFeatures property itself simply enables this mode, and the specific level of compatibility is set using the DisableFeaturesIntroducedAfter property.
  • DoNotEmbedSystemFonts- do not insert system fonts into the document (by default they are inserted for Russian, Japanese, etc.). Allows you to reduce the size of the document - but then users in a system where the Russian language is not installed will not be able to read this document.
  • EmbedTrueTypeFonts- a very useful property if you are working with a document in a place where exotic fonts are used (for example, in a publishing house). Inserting true-type fonts ensures that recipients of the document will see it exactly the same way as the creator.
  • Envelope- allows you to get a link to a special Envelope object, which is used to create mail envelopes.
  • Fields- the ability to get a link to the Fields collection of objects of the same name. Very useful when working with fields.
  • Footnotes- the ability to get a collection of footnotes.
  • properties Formatting…- what to show in the list of styles in the toolbar Formatting.
  • FormFields- similar to Fields, but in this case we get a link to the fields in the forms.
  • FullName- the full name of the object (along with the path to it in file system or Web). Read-only, of course.
  • GrammarChecked- mark the entire document as grammar-checked (effectively disable grammar checking for a given document). The same property exists for the Range object. A collection of errors caught during grammar checking can be obtained using the GrammaticalErrors property, and errors can be highlighted with a green wavy underline (if they are not already highlighted) using the ShowGrammaticalErrors property. For spelling errors, there are similar properties SpellingChecked, SpellingErrors and ShowSpellingErrors.
  • HasPassword- check whether a password has been assigned for the specified document. Password- assign a password. Due to extreme weakness password protection It is not recommended to use passwords in Word, Excel and Access.
  • Indexes- returns a collection of indices (that is, subject indexes) for a document.
  • Name- returns the document name (without the path to it).
  • OpenEncoding- returns the code page that was used to open the document. For the Russian language the default is, of course, 1251.
  • PageSetup- allows you to get a link to an object of the same name. It is used, of course, mainly in the implementation of printing.
  • Paragraphs- returns a link to a collection of paragraphs in this document.
  • Path- returns the path to the document in the file system (without name). May be useful to create another file on the same path.
  • Permission- the ability to access the Permission object, which allows you to manage the internal permissions system of a Word document (not file system permissions).
  • PrintRevisions- whether or not to print editor’s notes (corrections) along with the document. The default is print.
  • ProtectionType- check the security of this document (everything is allowed, or only comments, reading, changes in form fields, etc.). The protection itself is installed using the Protec()t method.
  • ReadOnly- no explanation required here. This property is read-only (because the corresponding attribute is set on the file system).
  • RemoveDateAndTime And RemovePersonalInformation- remove information about the date and time of changes made and all information about the user from the document (including document properties). May be useful when creating a sample file.
  • Saved- Very important property. Allows you to determine whether the document has changed since it was last modified.
  • SaveEncoding- allows you to explicitly specify (or get) the encoding that will be used when saving the document.
  • SaveFormat- allows you to obtain information about the document format (DOC, RTF, TXT, HTML, etc.). Read-only.
  • Sections- returns a collection of document sections. Sentences- the same for proposals. Properties work similarly Shapes , Styles, Subdocuments, Tables, Windows And Words .
  • Type- returns the document type (regular, template or Web page with frames).
  • Variables- another very convenient property. You can use it to save your service data along with the document, like custom attributes, but unlike custom document attributes, these properties are not visible to users.

Now - about the most important methods of the Document object:

  • Activate()- this method allows you to make the document you specify active (for example, for entering text).
  • AddToFavorities()- add a link to the document to the "Favorites" directory. It can be useful if the user works with it constantly.
  • CheckSpelling() And CheckGrammar()- run spell check and grammar check accordingly.
  • Close()- close the document. You can close with saving (by default), or you can close without saving (if you specify the appropriate parameter).
  • compare()- compare a document with another and generate editorial notes in places where differences are found.
  • DataForm()- the ability to edit data forms - that is, data that is separated in the document by field and line separators. Generally speaking, it is recommended to use data forms in Word only when absolutely necessary - Excel and Access are much more suitable for working with organized data.
  • DetectLanguage()- determine the language of the text. The check is carried out based on sentences, based on checking the words in them with the built-in dictionaries. This check occurs automatically when you enter text or open a new document. To recheck languages, the LanguageDetected property must be set to False.
  • FitToPages()- a very interesting method. The font size automatically changes so that the text takes up one less page. Can be used to eliminate "hanging pages" and other layout problems.
  • FollowHyperlink()- open the document you specified in the appropriate application (if HTML, then in Internet Explorer).
  • GoTo()- a very powerful method, exists for Document, Range and Selection objects. In the first two cases it returns a Range object, in the third it simply moves the text input pointer to the desired location. Can go to the top of the page, line, bookmark, comment, table, section, field, link, formula, etc. Maybe to a specific number of this object, first, last, next, etc. It is very convenient to use for placing the pointer in the right place for automatic text entry.
  • Merge()- the ability to merge two documents. The method is very complex and powerful, based on the use of editorial notes.
  • PresentIt()- opens this document Word to PowerPoint.
  • PrintOut()- Very complex method, which allows you to print the entire document or part of it. Accepts two dozen parameters (all optional). Can be used for Application, Document and Window objects.
  • PrintPreview()- put the document into preview mode.
  • Protect()- the ability to restrict changes to a document using a password or IRM.
  • Range()- a very important method. Returns a Range object (discussed below), taking as parameters the number of the starting character of the range and the number of the ending character.
  • Redo()- repeat the last action. Takes quantity as parameter recent actions, returns True if the retry was successful.
  • Repagify()- re-partition the document into pages. Typically used if automatic staking was previously disabled.
  • Save()- the meaning of this method is obvious. If the document has not yet been saved, a dialog box opens Save As.
  • SaveAs()- a very powerful and complex method. You can define the path for the saved document, its format, encoding, passwords for opening and changing the document, inserting fonts and much more. A very useful method, for example, for automatically converting documents.
  • Select()- allows you to simply select the entire document. This method exists for very large quantity objects, including Selection and Range.
  • TransformDocument() is an extremely powerful method, but only for programmers who are well versed in XML and XSLT. Allows you to apply an Extensible Stylesheet Language Transformation (XSLT) to a document, with which you can change anything you want.
  • Undo()- undo a certain number of recent actions. In terms of syntax and operating principles - complete analogue Redo().
  • UndoClear()- clear the undo buffer so that the user cannot roll back the actions taken.
  • UnProtect()- remove protection from the document (determined by the method Protect() or at graphical interface). Can be very useful before programmatically making changes to a protected document.

The Document object has only three frequently used events - New() (can only be defined for a template, triggered when a new document is created based on this template), Open() and Close(). All these properties are obvious and initially available in the code editor window Visual Basic.

10. Programming in Word

10.1 Why program in Word

Creating VBA applications in Word, typical situations

Word is the oldest and most popular app, included in Microsoft Office. In most organizations, users prepare documents in Word.

From a programming point of view, Word is primarily a tool for producing reports on databases. In this case, a report is any document that is generated on the basis of information from the database, for example, an agreement, an acceptance certificate, a cash receipt order, an announcement for a cash contribution, an order to the accounting department, an invoice, etc. Of course, reports that can be generated in Word also include documents with summary data - period reports, statements, etc.

The author had to create applications with reports developed in a variety of software products - Microsoft Access, Crystal Reports, Microsoft Reporting Services, etc. If your application generates reports to databases in Microsoft Word, then, most likely, such reports will not be the fastest in terms of their generation and not the simplest in terms of programming. But they will definitely be the friendliest towards the end user. Why?

Very often at an enterprise there is a need to correct just a couple of lines in the report form - for example, instead of “Director” put “Acting Director”. If the report was created in Crystal Reports or Microsoft Reporting Services, you will need to contact the developer immediately. And after some time I.O. will be confirmed as director, and the developer will have to edit the report again.

If the report is initially created in a Word document, then the user can always make the necessary changes to the created document - the vast majority of users in the enterprise know how to work in Word. There is no need to urgently look for a developer anymore.

There are other benefits to producing reports in Word. As a rule, when producing reports in Word, values ​​from the database are substituted into the report template, which is stored in the database or file system (in a *.dot file). If the report format is complex, with a lot of specific design (for example, an announcement for a cash contribution), then it is much easier to prepare its template in Word than, for example, in Crystal Reports or Reporting Services.

Another software application Word - working with different document formats. Word can work with documents of the most different formats. These capabilities can be used for mass processing documents.

A case from practice: in a directory on disk we have collected several hundred “various-sized” documents from different users. Some of them were created in Word different versions, some are just text files, some documents are in HTML, XML or EML formats (messages Email). The enterprise has implemented a document management system based on SharePoint Portal Server and we need to bring all these documents to a single format (Word 2003) and upload them to SharePoint Portal Server. Of course, without automation in such a situation you will have to tinker for a very long time.

The third software application of Word is formatting documents, for example, programmatically applying styles, searching and replacing sections of text in many documents at once, working with document structure, etc. Typically, such tasks are set in publishing houses, for example, when preparing manuscripts.

9.3. Visual Basic Editor

After recording the macro discussed above, the Normal template was added next text macro:

Sub Arial_10_bold()

“ Arial_10_bold Macro

“ Arial 10 Bold

With Selection.Font

Underline = wdUnderlineNone

UnderlineColor = wdColorAutomatic

StrikeThrough = False

DoubleStrikeThrough = False

Outline = False

SmallCaps = False

AllCaps = False

Color = wdColorAutomatic

Engrave = False

Superscript = False

Subscript = False

Animation = wdAnimationNone

Surely, to users unfamiliar with programming, such text will seem very complex, but upon closer examination it turns out that this is a simple set of parameters that are set or not set. Set parameter is denoted by the word True, and unspecified by False.

To record macros, as for other commands, Microsoft Word uses the Visual Basic for Applications (VBA, Visual Basic for Applications) language. A macro is a set of commands and statements in VBA. Each command and action in Microsoft Word is represented as strings in VBA format, and the process of recording a macro also involves the formation of such strings. Thus, the user has the opportunity to change or create a macro without re-execution the entire procedure. Although VBA macro can be created in any text editor; do not neglect the ability to record a macro in Word. Macro created by Microsoft help Word, you can add new commands and functions, and you can also learn the VBA language using such macros.

Macros can be edited using special utility, which is included with Microsoft Office, is the Visual Basic editor (Fig. 9.10).

Rice. 9.10. Visual Basic Editor Window

This program contains features that allow you to work with a macro: test, debug, run. Using this editor, you can add, change and delete objects in macros, create custom dialog boxes, debug the code of program procedures, view and select components of current projects and libraries, determine the appearance and behavior of macro objects at run time, and much more.

You can open the Visual Basic Editor window in several ways, for example, by clicking the Visual Basic button on the Developer panel.

From the book Programming author Kozlova Irina Sergeevna

3. Visual Basic Variables In Visual Basic, variables accumulate information (values). When they are used, Visual Basic takes up an area in the computer's memory that is intended for storing this information. Variable names made up of characters can be up to 255 characters long.

From the book Windows Registry author Klimov Alexander

Visual Basic Registering dll and ocx files This note will be useful to developers. If you often have to work with ocx files (as well as dll files) that require registration in the registry using REGSVR.EXE, then it will be much more convenient to make a corresponding entry in the registry than

From the book The C# 2005 Programming Language and the .NET 2.0 Platform. by Troelsen Andrew

The Visual Basic 6.0 Approach With a genuine desire to enjoy a simpler life, many programmers have moved away from the "framework world" of C(++)-based applications to more user-friendly languages ​​such as Visual Basic 6.0 (VB6). The VB6 language has become popular because of what it provides

From the book Windows Registry author Klimov A

From the book BPwin and Erwin. CASE development tools information systems author Maklakov Sergey Vladimirovich

Visual Basic 6.0 In Visual Basic 6.0, unlike the fifth version, the Code and Object windows appear in a normal, not expanded form. And every time you start VB6 you have to open these windows. You can force these windows to open automatically every time you start them. Create in the appropriate section

From the book VBA for Dummies by Steve Cummings

2.4.2. Code generation in Visual Basic ERwin supports code generation for MS Visual Basic versions 4.0 and 5.0. The source of information when generating forms is model ERwin. Using ERwin allows you to simultaneously describe both the client part (objects that display data on the screen),

From the book Programming for Pocket PCs author Volkov Vladimir Borisovich

What's visual in Visual Basic for Applications? Fortunately, VBA largely eliminates the need for tedious typing of code. In some cases, you write down the commands that are needed in the application and use them as a starting point when creating a new program.B

From the book Delphi Virtual Library by the author

VBA vs Visual Basic Besides the fact that VBA doesn't allow you to create individual applications, one of the main differences is that programs written in VBA are slower than programs written in Visual

From the author's book

Differences between VBA and Visual Basic VBA has a lot in common with Visual Basic, its older brother designed for creating independent applications. And since the languages ​​are similar, you can transfer most of your VBA programming skills to Visual Basic. However, you should remember

From the author's book

Invoking the Visual Basic Editor The Visual Basic Editor serves as a command center for working in VBA. You should be in it when developing VBA forms, creating VBA code, testing and debugging VBA programs. You'll be an expert in using the Visual Basic Editor after reading Chapter 5, but for now

From the author's book

A Brief Introduction to the Visual Basic Editor Your first time using the Visual Basic Editor can be confusing. The presence of menus and toolbars at the top of the screen will probably seem familiar to you, but what does this abundance of windows mean? Predict them mutual arrangement

From the author's book

Chapter 5. The Visual Basic Editor at your service. In This Chapter...~ Finding Commands in the Visual Basic Editor Menu System~ Displaying, Moving, and Customizing Toolbars~ Understanding and Using Dock Toolbars and Windows~ Battling Crowds of Visual Basic Editor Windows~

From the author's book

Visual Basic Editor User Interface The Visual Basic Editor is standard Microsoft fare—menus, toolbars, and keyboard shortcuts look and operate very similar to Microsoft Office. You'll feel right at home if you use VBA with Office applications.

From the author's book

eMbedded Visual Basic 3.0 Development Environment For brevity, the abbreviation eVB will be used in this chapter to refer to the eMbedded Visual Basic 3.0 environment. You can launch eVB either using the Start menu command (Start? Programs? Microsoft eMbedded Visual Tools ? eMbedded Visual Basic 3.0), or search for in the installation folder

From the author's book

Differences between eVB and Visual Basic for. NET Basically, the differences between VB.NET and eVB are related to the integration of the VB language with the Compact Framework and are determined precisely by the internal structure of CF itself. Data types In eVB there was one single data type for all occasions, Variant, which eVB inherited from VB Script. Visual

From the author's book

Delphi and Visual Basic 1. Is there a Delphi equivalent to the Visual Basic control array? No. Delphi components do not have an Index property like VB. However, there are three main reasons why you would want to use them in VB, and there is a solution for each of them in Delphi. Reason 1. You want

This book will help you master the VBA integrated development environment and learn how to program in VBA using objects, their properties, methods and events. The programming techniques discussed are illustrated with examples that you can immediately try out in practice. You will be able to apply the knowledge gained to configure and improve popular office applications, including Office applications XP and for creating your own applications.

The book is intended for those who want to quickly and effortlessly learn to program for Windows using VBA.

Book:

Working with text in Word VBA

Working with text in Word VBA

The Range and Selection objects are the starting points for almost any operation you can do with text using Word VBA. Some of these actions can be applied to documents as a whole, but in general you need a range or selection before you make changes.

Range and Selection objects have a lot in common, but there are a few key differences. Both objects represent contiguous sequences of characters on which you can perform various operations. Both objects have many common properties and methods. However, some properties and methods are unique to selections and others are unique to ranges. Another significant difference is that a Selection object corresponds to a selection in a window area: text, a graphic, or any other object, while Range objects exist independently of the selection and always contain text.

Use the Selection object if your procedure depends on the user, for example, the user must specify the text on which certain actions will be performed, or if you need to show the user exactly what text will be changed. In other situations, Range objects are much better suited. They provide higher speed execution of programs and is less intimidating to the user: Word updates the screen contents whenever the contents of the selected area change, and the screen contents are not updated when the range is changed. Additionally, range changes are not reflected in user-created selections.

Despite their differences, Selection and Range objects can be created from each other. This feature is extremely important because many editing functions only work with ranges. In contrast, the only way to display the contents of a range to the user is to highlight it. Use the following simple techniques.

* To select a range, use its Select method. For example, for a RangeR object the command is RangeR. Select.

* To access a range that represents the same content as the selected area, use the Range property.

Remember: if a method relating to text data is called on a range and you want to apply it to the selection, simply include a Selection statement in your code. Range. MethodName.

Word VBA offers a variety of methods for moving and resizing ranges and selections. In this section I consider only the most important of them; You will have to consult the help system for other methods.

The Expand method expands an existing range or selection by adding a block of text to the end. A block can be a character, a word, a paragraph, or anything else. You can only add one predefined block; In addition, adding such blocks at the beginning of a range or selection is not allowed.

To add a word to the highlighted area that will immediately follow it, use the following instruction:

Selection.Expand(wdWord)

You can use any of the following constants to extend an object; wdCharct er, wdWord, wdSentence, wdParagraph, wdSection, wdStory, wdCell, wdColumn, wdRow, wdTable, and (for Selection objects only) wdLine. The default is the wdWord constant.

Now there's a sticky point we should address: Selection objects (but not ranges) also contain an Expand method. This method includes the appropriate Word tool, which allows you to expand the selected area as you move the mouse pointer. Each time the program calls the Extend method, the selection is expanded by the block of text that immediately follows the insertion point: the current word, sentence, paragraph, selection, or entire document. If you specified the argument as a single character, such as Selection.Expand("C"). the selected area will be expanded to the first encountered specified character.

Word VBA allows you to redefine the start and end of a range or selection. Just keep in mind that methods that include the word Move in their names change the location of the range or selection: they do not move the text contained in the specified object.

The Move method changes the range or selection by starting to shrink it, marking its location, and no longer having any text in it. The location coincides with the beginning of the original object. The Move method then moves the "compressed" object according to your instructions. Once the move is complete, you can use the Expand and Mover,nd methods to fill the object with text.

The following example moves a named range back two paragraphs in the document. Note that you are using a named constant as the value of the Uni t argument (for a list of all valid named constants, see

"Extending ranges and selections" earlier in this chapter). The Count argument is a positive integer if you want to move the object forward through the document (that is, toward the end), or a negative integer if you want to move the object backward through the document. In the example below, the arguments are not enclosed in parentheses because the method's return value (the number of elements moved) is not used:

oTheRange .Move Unit: = waParagraph, Count, : = -2

MoveStart methods. and MoveEnd work much the same way as the Move method, only they change the starting or ending point of a range or selection, respectively. The following instruction will move the beginning of the selection three words closer to the end of the document:

Select-on.KoveStart Unit:= wdWord, Count:= 3

Note that if you move the starting point of an object to the end, Word will shrink the range or selection and move it according to the instructions provided.

Another pair of methods, Start Of or EndOf, will shuffle or expand the start or end of a range or selection. The Start Of method moves the start of the object back to the start of the current block, while the EndOt method moves the end of the object forward to the end of the current block.

You can use the Extend argument with any method to control what Word does. If the shuffled side of the object is already on the edge you're trying to move it to, nothing happens. Use the wdMove constant to shrink an object, or the wdExtend constant to move only the specified side. Below is a relevant example:

Selection. Start Of Unit:= wdSentence, Extend:= wdMove

Very often you need to compress a range or selection to a point that does not contain any text. Technically speaking, a collapsed range or selection is one whose starting and ending points are the same. Compressing such objects is important in situations where you need to insert a field, table, or other element before or after a selected area or range without replacing the text. (You can insert plain text, new paragraphs, and some other items into the "uncompressed" range or selection.)

Use the Collapse method to shrink a range or selection. You can shrink an object to its starting or ending point using optional argument Direction. The following statement shrinks the selection to its starting point:

Selection.Collapse

And this example shrinks the selection to its end point:

Selection.Collapse(Direction:=wdCollapseEnd)

If you collapse a range that ends with a paragraph mark to its end point (using the wdCollapseEnd constant), Word will place compressed range after the paragraph mark (this means the compressed range will be in the next paragraph). If you want to place something before the original range's paragraph mark, you must first move the range back using the MoveEnd method, using a statement like this:

Range.MoveEnd Unit:= wdCharacter, Count:= -1

Deleting all the text in a range or selection is easy: just use the Delete method of the corresponding object. You can also use the Cut method if you want to remove text and place it on the clipboard. Of course, Soru's method copies the text to the clipboard without affecting the text in the range or selection.

You can paste text previously placed on the clipboard into any range or selection by using the object's Paste method. If the destination object has not yet been compressed, the pasted text will simply replace the original text in the object, just as it does when you run the Paste command in Word.

Although using the clipboard to transfer text from one place to another seems quite common, this method is not always the most effective. It is much more convenient to use the Text or FormattedText properties of a range or selection. Set these properties to the range or selection containing the text you want to convey, and that's it. The destination object must be compressed until the text passed must replace existing text in the object.

The following code snippet transfers the text from the selection to a compressed range bound to the bookmark (the fourth line of code does the transfer operation). Only the text itself gets into the new location; any formatting is lost:

With ActiveDocument.Bookmarks("TheBookmark")

ActiveDocument.Range(Start:=.Start, End=.Start)

RangeY.Text = Selection.Text

To pass along the text and format it, simply replace the Text property with the FormattedText property.

The easiest technique to remember for adding text is to set the Text property of the range or selection to the text you choose to insert. This is illustrated by the example shown below:

Range2.Text = "Hey, hey! But there's no one at home!"

Just remember that using the Text property will replace anything existing on the object. To avoid this (unless you really want to replace existing text), shrink the object first.

Use the Insert Before or Insert After methods of a Range or Selection object to insert text at a specific location in the document without affecting existing text. These methods allow you to insert new text immediately before or after the specified object, respectively. Word includes the pasted text in a selected area or range.

When using either method, the only argument is the text you want to insert. The following code snippet inserts a new paragraph containing the words Dairy Entry at the beginning of the selection (note the use of the VBA constant vbCr to add a paragraph mark). After this, a new paragraph is added to the end, which begins with the current date. If you selected an entire paragraph before executing this code, the paragraph containing current date, will appear after the paragraph mark in the highlighted area.







2024 gtavrl.ru.