Variables that are declared implicitly are specified as the Variant data type. If you specify a data type for a variable or argument, and then use the wrong data type, a data type error will occur. To avoid data type errors, either use only implicit variables the Variant data type or explicitly declare all your variables and specify a data type.
The latter method is preferred. Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback. The variant has a special sub type called string variant that can be used to hold variable length strings. The Empty data type is the default value when you declare a variable as a Variant. You can perform operations on Variant variables but you need to be careful.
Arithmetic operations or functions can only be performed on numerical values. Variant variables with numbers require 16 bytes of memory. Variables of the Variant data type with characters usually require 22 bytes of memory plus the memory required by the string. And Decimal data is something of an exception: it's only available as a subtype of the Variant data type. The Empty subtype is automatically assigned to new Variant variables when you declare them, but before you explicitly assign a value to them.
For instance, in the code fragment:. In addition, a variable's subtype is Empty if it has been explicitly assigned a value of Empty, as in the following code fragment:. Null is a special data subtype that indicates a variable doesn't contain any valid data. Usually, a variable is assigned a null value to indicate that an error condition exists. In order for its subtype to be Null, a variable must have a Null value assigned to it explicitly, as in the following line of code:.
A Null value also results from any operation in which the value of one or more of the expressions is Null, as the following code fragment shows:. The Error subtype is used to store an error number. Error numbers are generated automatically by VBA, and can then be used by your error handling routine.
Error-handling routines are discussed in Chapter 6, Error Handling. Having the variant data type take care of your data typing is all well and good, but what happens when you need to know exactly what type of data is stored to a variable?
If you look at the formula bar, you will see that Excel has brought in A1, C1 and D1 as numbers formatted for currency. So even though you declared your variables as variants, Excel cleverly knew to bring them in as numbers. Variant variables take more memory and slow down your program. The Variant data type is automatically specified by the type of data it takes in — so in the four variables we created, three of them would have been string variables and one would have been a number variable.
Variant variables take in any data — which might make your code more difficult to debug. Your email address will not be published.
0コメント