Declaring Variables

In the last section, you learned how to use unchanging values called constants to specify formatting options in your macros. In this section, you'll learn how to create temporary storage containers called variables to store information that is updated periodically as your macro runs. Variables are useful because they let you assign a short, easy-to-remember name to a piece of data you plan to work with. Variables can hold the following types of information:

  • Numbers or words that you assign to your macro when you create it, such as an age or important date
  • Special values that the user enters when the macro runs, such as a name or heading title
  • Information from an Office document, such as words, paragraphs, cells, or slides
  • The result of a specific calculation, such as the amount of sales tax that is due on a purchase

We'll cover the process of declaring and using variables in the next few sections.

Making Reservations for Variables: The Dim Statement

Before you use a variable, you need to make a reservation for, or dimension, it in your macro. You accomplish this by placing the Dim keyword and the name of the variable at the beginning of your macro. Such an action reserves room in memory for the variable when the macro runs, and it lets Visual Basic know what type of data it should expect to see later.

For example, the following statement creates space for a variable named FullName in a macro:

 Dim FullName 

By default, Office creates variables in a general purpose format, or type, called Variant. The Variant type can adapt itself to a variety of data formats, including numbers, words, dates, and so on. Although you can specifically declare your variables to be of an exact type to save memory, you'll rarely need to do so in Office macros.

Putting Variables to Work

After you declare a variable, you are free to assign information to it in your code. For example, the following program statement assigns the string Clare of Assisi to the FullName variable.

 FullName = "Clare of Assisi"  

After this assignment, you can use the FullName variable in place of Clare of Assisi in your code. For example, the assignment statement

 Selection.TypeText Text:=FullName 

would insert Clare of Assisi into the current document using the TypeText method of the Selection object.



Running Microsoft Office 2000 Small Business
Running Microsoft Office 2000
ISBN: 1572319585
EAN: 2147483647
Year: 2005
Pages: 228

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net