Create A Constant

ou can create constants to refer a value, or a string that never changes. For example, given that a week always contains seven days, you can declare a constant with a value of 7 when you place that value in a procedure.

Just as you do with variables, you declare constants with a specific data type. In fact, constants use the same data types that variables use. If you do not specify a data type for a constant, VBA treats the value as a variant. Because constants never change, the functionality of your code to specify a data type improves. For more information, refer to the section "An Introduction to VBA."

Unlike a variable, you cannot alter a constant's value after you declare that constant. For example, if you assign the constant NewVar a value of 32 and attempt to reassign it a value of 45 you receive an error message when your code executes.

Although VBA allows you to declare constants anywhere in your code, consider declaring them at the beginning of the procedure. You can declare multiple constants on one line of code by placing a comma between each constant definition. For example, the following code declares two constants: Const NewString = "Excel Macros", Version As Integer = 2002

You can name constants using the same naming rules as variables. Essentially a constant can contain as many as 255 characters in length and use both alphabetical and numeric characters. For more information, see the section "An Introduction to VBA" earlier in this chapter.

By default, a constant value is private and only available for use within a particular procedure or module for constants declared at the code module level. You can make constants public and therefore useable by other procedures within the same workbook project by placing the Public keyword before the Const statement.

CREATE A CONSTANT

CREATE A CONSTANT

Grand Miroir Rectangulaire

habetic ] categorized |

Module3

-*SÎ Modules Module3 VBAProject {OfficeExi

B-Ö Microsoft Excel Ob|e I Hg Sheetl (Sheet 1) I Law

< Type the name of the constant.

habetic ] categorized |

Module3

□ Position the cursor after the Sub statement of a subroutine.

Type Const.

< Type the name of the constant.

Note: See the section "An Introduction to VBA" for more information for naming variables and constants.

Sheet2 (5heet2)_^J 5heet3 (Sheet3)

-*SÎ Modules Module3 VBAProject {OfficeExi

B-Ö Microsoft Excel Ob|e I Hg Sheetl (Sheet 1) I Law

Create_Constant

S lib Create Constant ( ) Const HewConsteint | ks | Dace |

I Type a question For help

iM aies

I I IJE-P." I jBuJa.l llfflHim... B]Ch,pO. I JOIIic. |

□ Type As after the constant's name.

Type your constant data type.

Note: See the section "An Introduction to VBA" for more information.

0 0

Post a comment