Tuesday, October 2, 2012

What are the Various Methods used to Declare Variables in VBA

How to declare the Variables in VBA
'Generally Variables Declared Using Dim Statement. We should declare all variables with specific data types, such as String, Long, or Double.We can declare 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, as shown below :
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.

Thanks, Tamatam

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.