A variable is a named location in memory. A variable allows us to store data that is input or calculated. Variables can vary, or change.
Before a variable can be used, it must be declared. To declare a variable, first decide what type of information you want to store:
- Whole numbers, number with no decimal places are Integer.
- Numbers with decimal places are called Double.
- Single letters such as "Y" or "N" are Char (character).
- A variable that can only have the values True and False is Boolean.
- Words, such as "Hello", or a person's name are String.
After deciding on the type, the next thing a programmer must do is decide on a variable name.
- A variable name must start with a letter of the alphabet.
- After the first letter, there can be additional letters, digits and underscores.
- There cannot be any spaces in a variable name.
- Words that have a special meaning in Visual Basic such as me or backColor cannot be used to name variables.
- The name of the variable should indicate its purpose. Variable names like a, b and c are not very good names for variables unless you are using them for the three sides of a triangle.
- If two words are joined together (you cannot have any spaces), a capital letter for the second word or an underscore can improve the clarity.
Example: hoursWorked, state_tax, and dueDate are all good variable names.
- It will be easier to remember the names if you develop a particular style and stick to it.
Variables are declared with the keyword Dim. Some variable declarations are shown below:
Dim numPackages As Integer = 12
Dim message As String = "Hello World"
Dim ready As Boolean = False
Dim hourlyRate As Double = 12.25
Dim grade As Char = "A"
In addition to the types listed above you will also sometimes declare variables to be one of the special types built-in to Visual Basic:
Dim myFavColor As Color = Color.Pink