Vba Variables Constant and Data types in Excel VARIABLES In Excel VBA, variables are areas allocated by the computer memory to hold data. Data stored inside the computer memory has 4 properties: names, data type, value and address. Each variable must be given a name. To name a variable in Excel VBA, you have to follow a set of rules, as follows: Variable Names The following are the rules when naming the variables in VBA It must be less than 255 characters No spacing is allowed It must not begin with a number Period is not permitted Space is not allowed It should not be a keyword. Examples of valid and invalid variable names are displayed in below table DATA TYPES In VBA, we need to declare the variables before using them by assigning names and data types. There are many VBA data types, which can be grossly divided into two
types, namely the numeric data types and the non-numeric data types. i) Numeric Data Types Numeric data types are types of data that consist of numbers, which can be computed mathematically with various standard arithmetic operators such as Addition, Subtraction, Multiplication, Division and more. In VBA, the numeric data are divided into 7 types, which are summarized shown in below table. Data Type Size in Memory Description Range of Values Byte 1 byte Represents an unsigned (nonnegative) number - often used for binary data 0 to 255 Integer 2 bytes Integer (no decimals) -32,768 to +32,767 Long 4 bytes Long Integer (no decimals) Single 4 bytes Single Precision Floating Point Number Double 8 bytes Double Precision Floating Point Number Currency 8 bytes A Floating Point Number with a fixed number of decimal places -2,147,483,648 to +2,147,483,647-3.4e38 to +3.4e38-1.8e308 to +1.8e308-922,337,203,685,477.5808 t o +922,337,203,685,477.5807 From the above table, it is clear that you can save on memory by using specific data types (e.g. Integers rather than Longs, or Singles rather than Doubles). However, if you are planning to use the 'smaller' data types, you must be sure that your code will not encounter larger values than can be handled by the chosen data type. ii) Non-numeric Data Types Nonnumeric data types are summarized in below table
Data Type Size in Memory Description Range of Values Date 8 bytes Date & Time - The Date type is represented internally by a floating point number. The integer part of the number represents the date, and the decimal portion represents the time. Boolean 2 bytes A simple True or False value Object 4 bytes A reference to an object String varies Holds a series of characters. The String type can be defined to have a fixed or a variable length, although it is most commonly defined to have a variable length Variant varies Can hold Dates, Floating Point Numbers or Strings of Characters, and should therefore be used when you are not sure what type of data to expect. 1st January 100 to 31st December 9999 True or False Any Object Reference Fixed - Up to 65,500 characters Variable - Up to approx. 2 billion characters Number - same as Double Type String - same as String Type Declaring Variables You can declare the variables implicitly or explicitly. For example, sum=text1.text
means that the variable sum is declared implicitly and ready to receive the input in textbox1. Other examples of implicit declaration are: volume=10 label= Dreams. If the data type is not specified, VBE will automatically declare the variable as a Variant (Variant means the variable can hold any numeric data type). On the other hand, for explicit declaration, variables are normally declared in the general section of the code window using the Dim statements. Here is the syntax: Dim Variable_Name As Data_Type Note that in the above line of code, Variable_Name should be replaced by your actual variable name and Data_Type should be replaced by one of the above listed data types. For example: Example: Dim Dreams As String Dim ename As String Dim fnumber As Integer Dim snumber As Integer Dim sumall As Integer Dim bdate As Date You may also combine them into one line, separating each variable with a comma, as follows: Dim Dreams As String, ename As String, fnumber As Integer. For string declaration, there are two possible formats, one for the variable length string and another for the fixed-length string. For the variable-length string, just use the same format as mentioned above. However, for the fixed-length string, you have to use the format as shown below: Dim VariableName as String * n Where n defines the number of characters the string can hold. For example, Dim yourname as String * 10
mean ename can hold no more than 10 Characters. In this example, we declared three types of variables, namely the string, date and currency. Private Sub CommandButton1_Click() Dim fname As String, bdate As Date, Salary As Currency fname = "ABC" bdate = "23 Nov 1981" Salary = 1000 Range("A1") = fname Range("A2") = bdate Range("A3") = Salary End Sub DECLARING CONSTANT Constant is similar to variable except that it has a fixed value that will never change. For example, you might use the constant "Pi" to store the value 3.14159265... The value of "Pi" will not change throughout the course of your program, but it is useful to store this value in a Constant for ease of use. Also, we might use a variable named "svat_rate", to store the VAT Rate to be paid on purchased goods. The value of svat_rate may vary, depending on the type of goods. Constants are declared in a similar way, except a constant should always be assigned a value when it is declared. Examples of the declaration of constants in VBA are: Const imaxcount=5000 Const imaxscore = 100 REASONS TO DECLARE VARIABLES Excel does not force you to declare variables. By default, all variables in Excel will have the Variant type, and can be assigned a number or text. Therefore, at any point during your program, you can use any variable name (even if it has not been declared), and Excel will assign the Variant type to it. However, it is not good programming practice not to declare variables for the following reasons:
Memory & Calculation Speed: If you do not declare a variable to have a data type, it will, by default, have the Variant type. This takes up more memory than many of the other data types. While a few extra bytes per variable might not seem to be a lot of memory, it is not uncommon for programmers to have thousands of variables in their programs (especially when you start to use arrays). Therefore, the additional memory used to store Variants instead of Integers or Singles, can add up significantly. Variant data types also take more time to process than some of the other data types, so if you have thousands of unnecessary Variant data types, this can slow down your calculations. Prevention of 'Typo' Bugs: If you always declare your variables, then you can use the VBA Option Explicit (see below) to force you to declare variables. This will prevent you from introducing bugs into your code by accidentally typing a variable name incorrectly. For example, you might be using a variable called "svat_rate" and, when assigning a value to this variable, you might accidentally type "VATRate = 0.175". From this point onwards, you are expecting your variable "svat_rate" to have the value 0.175, but of course it doesn't. However, if you had been using the VBA option Explicit to force you to declare all variables before using them, this error would be highlighted by the VBA compiler, as the variable "VATRate" would not have been declared. Highlighting Unexpected Data Values: If you declare a variable to have a specific data type, and you attempt to assign the wrong type of data to it, this will generate an error in your program which, if not handled within your code, can cause your programme to crash. While this may initially seem to be a good reason not to declare variables, it is actually useful to know as soon as possible if your variable receives an unexpected data type. Otherwise, if the program continues to run, you could end up with incorrect or unexpected results at a later time, when it is likely to be much more difficult to detect the causes of the errors. Also, it is possible that the macro may complete with incorrect results, and you may not notice the error at all - and continue to work with incorrect data!
It is therefore preferable to detect the unexpected data type at an early stage and add code to handle this appropriately. Due to the reasons listed above, it is recommended that you always declare all variables when programming in VBA, and use the Option Explicit (see below) to ensure that all variables in the code are declared. THE USE OF OPTION EXPLICIT The use of Option Explicit is to help us to track errors in the usage of variable names within a program code. For example, if we commit a typo, VBE will pop up an error message Variable not defined. Indeed, Option Explicit forces the programmer to declare all the variables using the Dim keyword. It is a good practice to use Option Explicit because it will prevent us from using incorrect variable names due to typing errors, especially when the program gets larger. With the usage of Option Explicit, it will save us time in debugging our programs. If you want to always include the option Explicit at the top of every new VBA module that you open up, this can be done automatically via the 'Require Variable Declaration' option of your VBA editor. To activate this: In the Visual Basic Editor, select Tools Options...; Ensure the Editor tab is selected; Check the box next to the option Require Variable Declaration and click OK. Once the 'Require Variable Declaration' option is selected, the Option Explicit will automatically be inserted at the top of all new modules in the VBA Editor. When Option Explicit is included in the program code, we have to declare all variables with the Dim keyword. Any variable not declared or wrongly typed will cause the program to popup the Variable not defined error message. We have to correct the error before the program can continue to run. This example uses the Option Explicit keyword and it demonstrates how a typo is being tracked.
Option Explicit Private Sub CommandButton1_Click() Dim myname As String, pass As String myname = "John" pass = 12345 Cells(1, 2) = mynam Cells(1, 3) = pass End Sub The typo is mynam and the error message variable not defined is displayed. ASSIGNMENT STATEMENT (ASSIGNING VALUES TO THE VARIABLES) After declaring various variables using the Dim statements, we can assign values to those variables. The general format of an assignment is Variable=Expression The variable can be a declared variable or a control property value. The expression could be a mathematical expression, a number, a string, a Boolean value (true or false) and more. Here are some examples: firstnumber=100 secondnumber=firstnumber-99 username="john Lyan" userpass.text = password Label1.Visible = True Command1.Visible = false ThirdNumber = Val(usernum1.Text) total = firstnumber + secondnumber+thirdnumber SOURCE: http://www.excelfunctions.net/vba-variables-and-constants.html