You can find the Excel tips you're looking at Pro-business Excel VBA Programming by entering the keyword in the textbox below and clicking the "Google Search" button.

Sunday, August 5, 2007

Declaration of Variable

Variable Declaration’s general syntax is:

Dim VariableName As DataType

We can place more than one declaration on a line to save space. For instance, the following line
declares three variables:

Dim strFullName As String, dtBirthday As Date, byteMonth As Byte

Declaration of a variable is actually defining its data type. Variables are commonly declared with the DIM keyword. Other type of keywords are also used but it will be tackled in my future posting. Examples of variable declaration are as follows:

Dim strFullName As String
Dim dtBirthday As Date
Dim byteMonth As Byte
Dim intAge As Integer
Dim boolIsMarried As Boolean
Dim sglHeight As Single
Dim curMoney As Currency
Dim wbkPayables As Workbook
Dim chSales As Chart

VBA treats a variable as Variant whenever it is used without first declaring it. Or data type is not mention when declaring it, as in:

Dim IsMarried

Declaring a variable without a data type is not a good idea because it is a waste of memory. Waste of memory because the variable will use the memory size requirement for a Variant data type which is 16 bytes. Using the example above, if you intend to use the variable as a storage for a Boolean value but fail to declare it, the variable will use 16 bytes instead of 2 bytes. Fourteen (14) bytes are wasted. In a large program that is using hundreds of variant variables, memory waste is significant. Moreover, maintaining a Variant variable involves more overhead compare to specifically declared variable. Using Variant variable will result in bad performance of your program.



Click here to subscribe and receive Pro-business Excel VBA Programming tips.


If you like this post in Pro-business Excel VBA Programming, buy me a coffee.


0 comments: