The equal operator is fairly straightforward. Just remember that equal means exactly equal. If two values differ by even the slightest amount, they are not evaluated as equal. The two values 4. When using the Greater Than and Less Than operators remember that any negative number is less than any positive number.
This is easy to remember. The line has 0 in the middle, the positive numbers 1,2,3, and so on to the right, and the negative numbers -1, -2, -3, and so on heading off to the left. Pick any two numbers on this number line. The one on the left is always less and the one to the right is always more. The Not Equal operator tells you if any two variables are different, even by the slightest amount.
Not Equal can be used to determine if two dates or times are the same, if two files have identical names, or if the length of two files differ. It can be used anywhere you need to know if there is the slightest difference. Less Than or Equal combines two questions into one.
OR is shown in capitals to emphasize that if either of the conditions is met, the statement is True. Greater Than or Equal works in a similar but opposite manner. Logical Operators You use logical operators to build more complex logical constructs. Logical operators allow you to apply Boolean logic to your data, determining a final solution that is either True or False. VBA provides the following logical operators:. A full discussion of these constructs is provided in Chapter 7, but a quick overview is provided in the examples here.
The And operator returns a True value only if both operands are True, otherwise the result if False. Notice the use of parentheses in the example. Operations within parentheses are performed first and then the results are used in further calculations. This ensures that operations are performed in the order you intend. The Or operator returns a True value if either of the operands are True.
The Xor operator returns a True value when only one of the operands is True. It returns a False value whenever both operands are the same, whether they are both True or both False.
The Eqv operator returns a True value only if both operands are equal, otherwise the result is False. In all numeric situations the Eqv operator is the same as using an equal sign in a comparison. Eqv does not act as a comparison operator for strings, however. The Imp operator is the local implication operator. The Not operator differs from the other logical operators in that it does not require two operands. Instead, it performs a logical negation of a value. In other words, a True value is changed to False and vice versa.
Listing 4. String Operators Earlier you learned about comparison operators and how they can be used to compare numeric values. Comparison operators also can be used with strings, and then the result used in further computations.
In addition, VBA provides a way to concatenate combine strings together. Using Objects and Collections As mentioned earlier, Visual Basic for Applications is an object-oriented programming language.
This means that it works with objects and collections of objects. This may sound a bit odd, but it is no different than us as humans— we work with objects, as well. Consider your home for a moment; it contains many objects and collections of objects. For instance, if you walk into your kitchen you may find a dish on the counter. This dish is a single object, but it is also a member of a larger collection of objects referred to as dishes. You can do things with the single dish just like VBA can do things with a single object or you or you can do things with the entire collection of dishes just like VBA can do things with a collection of objects.
It is, after all, a word processor. While you may intuitively understand what a document is, VBA does not; remember that it can only do work with objects. Fortunately, Word makes certain objects accessible to VBA and allows them to be worked with. Documents are an example of the type of objects that Word makes available to VBA.
In fact, there are many, many different types of objects that Word makes available. There are literally hundreds of different objects that Word allows you to access through VBA. Follow these steps:. Display the Visual Basic Editor. With the Visual Basic Editor visible, press F1. Word displays the help system for VBA. On the main screen for the help system, click the Word Object Model Reference link.
What you see should be similar to what is shown in Figure Each of the topics listed in the Subcategories section is an object available in Word. You can figure out the purpose of most of the objects just by looking at their names.
For instance, you can probably figure out that the Shape object represents a graphic shape that you add to your document. This becomes apparent as you start to type VBA statements into the editor. This object is the top-level object in Word. It is called the Application object because it represents the currently running version of Word. Every other object belongs to the Application object.
You can probably figure out that a Document object represents a single Word document. This is a document that is open within the program; it is not an unopened document on your hard drive. Document objects belong to the Application object and they can contain many other types of objects. This is a very common object that belongs to many higher- level objects. This object represents whatever is selected within the document at the time that the macro is running.
Grouping Similar Objects Together Word automatically groups similar objects together into what are called collections. For instance, individual Document objects are grouped together in the Documents collection and individual Shape objects are grouped in the Shapes collection.
Each of these is a collection of individual objects. VBA allows you to access individual members of collections or to work with an entire collection. This makes it easier in the program to later work with the various members of the object.
Object members are described in the next section. To assign an object to a variable, you use the Set keyword. For example, you might want to work with the first paragraph of a document. You can define the variable you are going to use for this purpose in this manner: Dim rFirstPar As Range.
Paragraphs 1. This assigns the Range object of the Paragraphs 1 object of the Documents 1 object to the rFirstPar variable. This variable now contains the Range object and you can access that object using the variable at any time. Essentially, the rFirstPar variable contains the first paragraph of the document.
Understanding Object Members Objects or collections of objects can have a number of different members that belong to them. These members are of two primary types: methods and. Doing Operations with Methods The easiest way to look at a method is as some sort of process that Word allows you to perform using an object.
For instance, you might want your macro to create a new document. You do this by using the Add method for the Documents collection, in this manner: Documents. Note that you separate the object name in this case Documents from the method name Add by a single period. When this line is executed, VBA dutifully adds a new, empty document to the collection of open documents.
As you move from left to right on the line, each period you encounter represents another movement through the hierarchy. The number and type of methods available for an object depends on the nature of the object to which the methods belong. For instance, the Hyperlink object possesses a Follow method that is used to display the target of that hyperlink.
Working with Properties Each object in the Word object model possesses a group of properties. These are nothing but attributes or characteristics that belong to or describe the object.
For instance, in real life if you are looking at a dish in your kitchen, its characteristics might be its diameter, its depth, its color, or any number of other descriptors. These are, in the object-oriented world, properties of the object. In total, there are almost 30 different properties associated with the Envelope object.
They describe characteristics of the envelope, in exquisite detail. When creating programming statements in VBA, you refer to properties using the same technique that you refer to methods. An important concept about properties is that some of them can be written to you can change them and some properties can only be read. Finally, it is important to understand that some properties are fully objects in their own right. Paragraphs This line sets the sParStyle variable equal to the name of the style for the twelfth paragraph in the document.
In this instance, the primary object is Documents 1 , which is the first document in the documents collection. Everything after that point is considered a property of that primary object. Thus, Paragraphs 12 is a property of the primary object, even though it is an object in its own right.
Making Sense of Members Since there are hundreds of different objects available in the Word object model, there are thousands of different methods provided to work with those objects and even more properties for those objects.
It is impossible for a human. The options are shown in a drop-down list of members, with an indicator as to whether the member is a method or property. Remember that variables are called such because they can vary.
In VBA constants are of three types: literal, symbolic, or enums. Using Literal Constants Literal constants are very simple in nature. You can use them on the right side of most any operator. Obviously this formula ends up in the variable X being equal to 5, but it is not X on which you should focus. In this instance there are three constants, each surrounded by quote marks that are concatenated together and assigned to the sMyString variable. Creating Symbolic Constants Symbolic constants are similar to variables in that they are declared within a program and given a name a symbolic name, if you prefer that can subsequently be used in the program.
The Const keyword tells VBA that you are setting up a constant. It is followed by the name you want used for this constant sMyName , the equal sign, and the value you want used for the constant. As mentioned earlier, the values of constants cannot change within your program once they are set. If you try to change the value of a constant, VBA generates an error. VBA provides a wide variety of enums somewhere in excess of of them that are used for a wide variety of things.
Word provides somewhere around 2, different enumeration constants for its object model. Names of macros are very important, and this chapter is designed to help you understand all the ins and outs of the names you may consider.
VBA is fairly flexible in allowing you to name your macros. In fact, there are only three simple rules you need to follow:. It is also a good idea to not use a macro name that matches any existing VBA function or enum. Functions and enumerations are discussed in Chapter 6.
If you do so the results may be unpredictable. One good idea is to make sure that your macros all start with some unique letter sequence that makes sense for your system. For instance, you may want to start all your macros with your three initials.
Doing so allows you to easily differentiate those macros you created from any other macros that may be on your system. Renaming Macros At its heart a macro is nothing more than a series of instructions you want the computer to execute. It is a program that is run in the framework provided by Microsoft Word.
Word displays the Visual Basic Editor. In the Code window, use the Procedure drop-down list to choose the procedure you want to rename. The procedure you select is displayed in the window. Change the actual name in this line. Where Macros are Stored You know where Word stores your documents—on your hard drive or on some other storage medium, such as a thumb drive.
Instead, macros are stored as part of other files, much like graphics or text boxes are stored as part of a different file document files. Early in Chapter 2 you learned about modules and how VBA procedures are stored in those modules. You can store VBA modules with any type of Word document, whether it is a regular document or a template.
In fact, when you. This is a regular Word document that contains at least one VBA module. This is a Word template that contains at least one VBA module.
By default Word stores your macros as part of the Normal. How you do that depends on whether you are recording a macro or creating one from scratch. Specifying a Location when Recording a Macro In Chapter 1 you discovered how easy it is to record a series of actions as a macro. What you may not have realized was that as part of the recording process Word gives you the chance to specify where you want to save the macro you are recording.
To see where this occurs, start by displaying the Developer tab of the ribbon. Then click the Record Macro tool in the Code group. Word displays the Record Macro dialog box, shown in Figure Note that the dialog box includes a drop-down list called Store Macro In. If you click this list, Word provides a number of options for you. The top option is always All Document Normal. This is the default choice; it means that the macro is stored in the Normal.
The other options available in the drop-down list depend on how you are using Word at the moment. If you choose one of these as the place where your macro should be stored, then the next time you chose. When recording a macro you can specify where the macro is to be stored by using the Store Macro In drop-down list. Specifying a Location when Creating a Macro from Scratch Choosing where Word stores your from-scratch macros is similar to choosing where it saves your recorded macros.
The biggest difference is that you make the selection in the Macro dialog box instead of the in the Record Macro dialog box. You can then click the Macros In drop-down list to see places where macros can be stored see Figure If you compare Figure with what is shown in Figure , you can probably figure out how the various options correlate with each other. It is interesting to note that that wording of the available options is different, even though they do the same things.
Basically the meaningful options are as follows:. When creating macro from scratch you can specify where the macro is to be stored by using the Macros In drop-down list. This is the Normal template and is available to all documents at all times in Word.
This is the list of built-in Word functions. Each of your currently open templates is available in the drop-down list.
Each of your currently open documents is available in the drop-down list. Choose where you want your macro stored, and once you click on Create then Word opens the Code window for the appropriate module in that template or document. Event Handlers Objects within Word can have events handlers associated with them. An event handler is a special type of macro that is triggered executed whenever a particular event occurs. Most event handlers are associated with the special ThisDocument object, which exists for every document you create in Word.
Note the Project Explorer window, at the left side of the editor. The Project Explorer is explained in more detail in Chapter 4. Note that the Project Explorer shows each document you have open as a project. Locate the document project for which you want to create an event handler. Double-click the ThisDocument object, in the Project Explorer, for the document you located. A Code window for the document is opened.
Click the Procedure down-arrow see Figure to see the events that can be handled for the document. There are several other events that are available in the drop-down list, as follows:. Double-clicking the ThisDocument object opens a code window for that object.
Clicking the Procedure down-arrow shows a list of events available for the ThisDocument object. This event is triggered whenever an existing building block is inserted in the document.
This event is triggered whenever this particular document is closed. This event is triggered when a content control is added to the document. This event is triggered before updating the content in a content control, but only when the content comes from the Office XML data store. This event is triggered before a content control is deleted from the document. This event is triggered whenever the user enters selects a content control. This event is triggered whenever the user exits a content control by moving to a different content control or by moving to some other area of the document.
This event is triggered whenever this particular document is open and you then create a new document. This event is particularly helpful if it is associated with a template, as it is triggered whenever you create a new document based on the template. This event is triggered whenever the document is first opened.
This event is triggered when the document is synchronized with a copy of the document that resides on a document server. This event is triggered when each new XML element is added to the document.
This event is triggered before each existing XML element is deleted from the document. Most of the events for which you can create handlers are pretty advanced, having to do with things like remote servers, XML, and XML stores. Automatic Macros Besides the event handlers described in the previous section, Word includes a few names for macros that it considers special.
These special names, when given to your macros, perform tasks without any intervention on your part. These special macros that automatically run at predefined times are identified by special names. Otherwise, there is nothing different between these macros and any other you may write.
Here are the names you can give macros so that they run automatically. A macro that possesses this name is run whenever you open a document. A macro using this name is run whenever you close a document. A macro saved under this name is automatically run whenever you create a new document.
A macro that uses this name is run whenever you start Word. This name for a macro means that it is run whenever you exit Word. Why would you want to use these automatic macros? You might have some special tasks that need to be completed relative to a specific document. An easy way to do that is to simply create an AutoOpen macro and save it in the important document. The next time the document is opened the user is shown a message box with your request.
Changing Built-In Word Commands Word allows you not only to edit macros, but also to edit built-in commands. Word includes literally hundreds of built-in commands, many of which are executed whenever you use the various tools available on the ribbon tabs.
You can replace or augment these commands with your own macros. You perform the editing by following these steps:. Word displays the Macros dialog box. Using the Macros In drop-down list, select Word Commands. Using the command list, locate and select the command you want to edit. Once selected, the name should appear not only in the list of commands, but also in the Macro Name box at the top of the dialog box. Using the Macros In drop-down list, select where you want your edited command to appear.
For instance, you could select All Active Templates and Documents, or you could select a specific template or document name where your new command should be stored. The command name should still appear in the Macro Name box at the top of the dialog box. The Create button is not clickable until you perform step 4.
Word starts the Visual Basic Editor and shows the program instructions that make up the built-in command. Make your changes to the command. Note in step 5 that the program instructions that make up the built-in command are provided as a starting point for your editing. Any changes you make to the command are used, by Word, in preference to the regular instructions for the command. The macro consists of a single command line that saves the document. You may want to modify the code so that the document is saved in a particular location or so it is saved in multiple locations or so it is saved using some name you specify.
The ways in which you can modify the command are, literally, endless. Remember that the key to Word using your macro instructions in preference to the built-in command is the name of the macro.
A modified Word command is only in effect for the document in which you save the command or, if you save it in a template, if the template is associated with the document on which you are working. To get rid of your modified command, just delete it fully in the Visual Basic Editor.
Understanding the VBA 4 Environment Visual Basic for Applications offers a simple approach to programming macros that work within the framework offered by Word. With VBA you can quickly and easily create macros that automate common tasks and make processing your documents a snap. In this chapter you discover more about the environment in which VBA macros are run. Specifically, you learn how to use the Visual Basic Editor and everything that it offers. Regardless of whether you record macros and later edit.
The Visual Basic Editor uses the older, menu-based interface familiar to long- time Word users. The following sections examine each of those parts. The menu bar contains the major categories of tasks you may want to accomplish with the editor. You can select menus with either the mouse or the keyboard. To select a menu with the mouse, just point to the menu name and click the left button. A pull-down menu appears.
Using the keyboard, however, requires a little more information. Notice that the first character of each menu name in the menu bar is underlined. The underlined character is the access key for that menu.
In some other programs, these access keys are often called hot keys. To activate a menu, press. For example, to pull down the File menu, press and hold the Alt key and then press F. After you pull down a menu, notice that each menu item also has an access key.
The default setting disables macro from running, but warns you that macros have been disabled and gives you the option to turn them back on for that document. You can designate specific folders where macros can run by creating Trusted Locations, Trusted Documents, or Trusted Publishers. The most portable option is to use Trusted Publishers, which works with digitally signed documents that you distribute. For more information about the security settings in a particular Office application, open the Options dialog box, choose Trust Center , and then choose Trust Center Settings.
Some Office applications, like Outlook, save macros by default in a master template on your local computer. Although that strategy reduces the local security issues on your own computer when you run your own macros, it requires a deployment strategy if you want to distribute your macro.
When you choose the Macro button on the Developer tab, it opens the Macros dialog box, which gives you access to VBA subroutines or macros that you can access from a particular document or application. Another button on the Developer tab in Word and Excel is the Record Macro button, which automatically generates VBA code that can reproduce the actions that you perform in the application.
Record Macro is a terrific tool that you can use to learn more about VBA. Reading the generated code can give you insight into VBA and provide a stable bridge between your knowledge of Office as a user and your knowledge as a programmer. The only caveat is that the generated code can be confusing because the Macro editor must make some assumptions about your intentions, and those assumptions are not necessarily accurate.
Open Excel to a new Workbook and choose the Developer tab in the ribbon. Choose Record Macro and accept all of the default settings in the Record Macro dialog box, including Macro1 as the name of the macro and This Workbook as the location.
Choose OK to begin recording the macro. Note how the button text changes to Stop Recording. Choose that button the instant you complete the actions that you want to record.
Choose cell B1 and type the programmer's classic first string: Hello World. Stop typing and look at the Stop Recording button; it is grayed out because Excel is waiting for you to finish typing the value in the cell.
Choose cell B2 to complete the action in cell B1, and then choose Stop Recording. Be aware of the similarities to the earlier code snippet that selected text in cell A1, and the differences. In this code, cell B1 is selected, and then the string "Hello World" is applied to the cell that has been made active. The quotes around the text specify a string value as opposed to a numeric value.
Remember how you chose cell B2 to display the Stop Recording button again? That action shows up as a line of code as well. The macro recorder records every keystroke. The lines of code that start with an apostrophe and colored green by the editor are comments that explain the code or remind you and other programmers the purpose of the code.
VBA ignores any line, or portion of a line, that begins with a single quote. Writing clear and appropriate comments in your code is an important topic, but that discussion is out of the scope of this article. Subsequent references to this code in the article do not include those four comment lines. When the macro recorder generates the code, it uses a complex algorithm to determine the methods and the properties that you intended. If you do not recognize a given property, there are many resources available to help you.
For example, in the macro that you recorded, the macro recorder generated code that refers to the FormulaR1C1 property. Not sure what that means? Be aware that Application object is implied in all VBA macros. The code that you recorded works with Application. Select FormulaR1C1 in the recorded macro and press F1. The Help system runs a quick search, determines that the appropriate subjects are in the Excel Developer section of the Excel Help, and lists the FormulaR1C1 property.
You can choose the link to read more about the property, but before you do, be aware of the Excel Object Model Reference link near the bottom of the window. Choose the link to view a long list of objects that Excel uses in its object model to describe the Worksheets and their components.
Choose any one of those to see the properties and methods that apply to that particular object, along with cross references to different related options. Many Help entries also have brief code examples that can help you. For example, you can follow the links in the Borders object to see how to set a border in VBA.
The Borders code looks different from the recorded macro. One thing that can be confusing with an object model is that there is more than one way to address any given object, cell A1 in this example.
Sometimes the best way to learn programming is to make minor changes to some working code and see what happens as a result. Try it now. Open Macro1 in the Visual Basic Editor and change the code to the following. You do not need to save the code to try it out, so return to the Excel document, choose Macros on the Developer tab, choose Macro1 , and then choose Run. Cell A1 now contains the text Wow!
You just combined macro recording, reading the object model documentation, and simple programming to make a VBA program that does something. The VBA community is very large; a search on the Web can almost always yield an example of VBA code that does something similar to what you want to do.
If you cannot find a good example, try to break the task down into smaller units and search on each of those, or try to think of a more common, but similar problem. Starting with an example can save you hours of time.
That does not mean that free and well-thought-out code is on the Web waiting for you to come along. In fact, some of the code that you find might have bugs or mistakes. The idea is that the examples you find online or in VBA documentation give you a head start.
Remember that learning programming requires time and thought. Before you get in a big rush to use another solution to solve your problem, ask yourself whether VBA is the right choice for this problem. Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. Feedback will be sent to Microsoft: By pressing the submit button, your feedback will be used to improve Microsoft products and services.
Privacy policy. This reference contains conceptual overviews, programming tasks, samples, and references to guide you in developing solutions based on Word. Interested in developing solutions that extend the Office experience across multiple platforms? When editing Word files you might want to leverage tables as it is much easier to navigate around them in an automated way. This way you can guarantee a consistent and easy to navigate structure in Word. Is that normal?
Len gives you the number of characters, but the first character is 0. When I subtract 1 from Len, it works.
0コメント