Vba Programming Basics

You can quickly specify a variable's data type by using the VBA type declaration characters within the declaration statement. Using this method is basically a shortcut for typing the variable.

Example:

Dim NewVar%

Excel provides six different characters that you can use to specify the data type for a variable. In the sample declaration, which declares a variable containing integer values, the type declaration statement replaces the As datatype portion of the declaration statement.

CHARACTER

DATATYPE

Q. %

Integer

&

Long

!

Single

#

Double

@

Currency

$

String

You can shorten your VBA code by declaring variables using one Dim statement. In other words, you declare multiple variables on one line by typing Dim followed by each variable and the appropriate data type.

Example:

Dim Int1 As Integer, Int2 As Integer, Int3 As Integer

Although VBA allows you to lump a group of variables together using one Dim statement and one data type, it does not assign the data type you would expect. For example, you typically declare all three variables as integer.

Example:

Dim Int1, Int2,

Int3 As Integer

In reality, VBA only assigns an integer data type to Int3. VBA assigns the other variables a data type of variant.

— Switch to Excel and run the corresponding macro.

■ The message box displays the value to the variable you specified in step 8.

_O Type your variable name.

Type an equal sign (=) and a starting value for your variable.

| Type MsgBox(VarName), replacing VarName with the name of your variable.

■ The MsgBox function displays a dialog box.

— Switch to Excel and run the corresponding macro.

■ The message box displays the value to the variable you specified in step 8.

0 0

Post a comment