Tuesday, 2 October 2012

What are VBA Variables Declaration Methods

Be Aware about Variables Declaration Methods
'Generally Variables Declared Using Dim Statement.
'We should declare all variables with specific data types, such as String, Long, or Double.
'We can delcalre all variable using one Dim statement.

'VBA allows declaring more than one variable with a single Dim statement.
'I am saying it not so healthy,but others do prefer it.
'However, it is important to remember how variables will be typed. Consider the following code:

Dim A, B, C As Long

'You may think that all three variables are declared as Long types.
'This is not the case. Only C is typed as a Long. The variables A and C are typed as Variant.

This declaration is functionally equivalent to the following:

Dim A As Variant, B As Variant, C As Long
'You should use the "As Type" modifier for each variable declared with the Dim statement:

Dim A As Long, B As Long, C As Long
---------------------------------------------------------------------------------------------------------------------
Avoid Using The Variant Data Type :
'We should declare all variables with specific data types, such as String, Long, or Double.
'VBA supports the Variant data type that can hold any type of data.
'If you omit the As Type clause in a variable declaration, Variant is the default type.
'While it may seem useful, it increases processing time when encountered in code because behind the scenes,
'the compiler has added no small amount of code to test what type of data is actually stored in the variable.

'Moreover, using a Variant can mask possible "Type Mismatch "errors that should be caught during testing.
'Instead of using a Variant type, declare the variable with a specific data type

No comments:

Post a Comment

Follow Me by Email

ExcelKingdom-Popular Posts

ExcelKingdom-Random Posts