In the last article, we took a look at what the term ‘event-driven’ means. We saw that Visual Basic will only process code after a certain event takes place, and we saw a few tips that can make your programming-life easier. We also started off with a very basic calculator program.
This article, I’ll explain what variables are, why and how to use them, what different types of variables you can use, the scope of variables and finally we’ll look at constants.
Variables described
What are variables? According to the MSDN, a variable is A location in the computer’s memory where data is stored. Anybody got that? Let’s try clarifying that a little. Think of a variable as a wallet; a place where you temporarily store various things in (coins, bills, credit cards, pictures, business cards). Whenever you need one of those things, you retrieve it from the wallet, and when you’re finished with it, you can put it back in.
The same can happen with data in applications. Last article, we did not do anything with the number that was provided by the user. We just left it in the TextBox. We could have stored it in our computer’s memory, and cleared the TextBox. Another way to use variables would be by storing text that’s provided by a user.
Why use variables?
Good question. Why not just use the TextBoxes to store the data in? Well, look back at the calculator. If we’d store all numbers provided by the user in text boxes, we’d soon have a screen full of text boxes with various numbers in it. Instead, in the future, we will store the number in a variable and then clear the TextBox (thus indicating to the user that our program is ready to receive a new number).
Another reason to use variables would be because the memory is readily available for fast access. If something is stored in memory, it can be called or altered with great speed. If we’d just store our data in text boxes, the program would first have to read the number in the TextBox, then alter it, and finally put it back into the TextBox (Granted, this might seem like a marginal fraction of time, but in programming, you’re ideally looking for code that’s as optimized as can be. In the end, every millisecond you can spare counts).
Finally, Visual Basic offers a number of functions that can be used to alter data. Using variables, you can easily store the data, and use those functions on it.
How to use variables
Before you can use a variable, you have to declare it. That is, you have to let Windows know you want to reserve memory for storing data in, supply a name for the variable, and you have to tell Windows what type of data it will be (discussed in the variable-types-section). The way to do this is by using the keyword Dim. (Dim stems from earlier days, and is an abbreviation for Dimension, because you reserved a dimension of the memory. If you like, think of Dim as meaning ‘Declare In Memory’, which is a nice little shortcut that makes sure you’ll remember the ‘Dim’-keyword for now. (In a few weeks, you won’t even have to think about using Dim, it’ll be an automatic thing)).
To declare a variable that we’ll be using to store text in (A so-called string), we would use the following piece of code (the name of the variable would be strInput):
Dim strInput As String
This is called Explicit Declaration. Remember that when we installed VB, we checked the ‘Require Variable Declaration’ CheckBox? (This causes ‘Option Explicit’ to be written in the code window). Well, by checking that box, we made sure that every variable we will be using will have to be declared with the Dim statement. This ensures that if you try assigning data to, or calling data from a variable, Visual Basic will generate an error if the name of the variable doesn’t exist. When you create a variable, Visual Basic will (silently) create the variable with value ‘0’.
If you want to assign a value to a declared variable, you can do that the following way:
strInput = txtInput.Text or
strInput = “Hello!”
The text “Hello” is between quotes (“) because it’s a string. We have to let Visual Basic know exactly what text we want to store in the string, because the internal commands, functions, and keywords of Visual Basic could also be used within a string. Consider the following (try it out in VB if you want. You’ll receive an error):
Dim strText As String
strText = This is an example of how to use the keyword Dim in VB
See? Visual Basic has no idea of whether it would have to use Dim to declare something, or whether you were trying to store it within a string. The code will work if we add the quotes:
Dim strText As String
strText = “This is an example of how to use the keyword Dim in VB”
The quotes only have to be used in the case of strings. All the other variable-types require no quotes to be used.
Types of variables
Because there are various data-types to store, there are also various variable-types. The table below shows respectively the types of variables, the number of memory-bytes required to store the variables in, and the range of the values for each variable-type.
As you can see, any possible value you would ever want to store has been thought of. The default type for a variable, by the way, is Variant. So if you’d just declare a variable like this:
Dim strInput
The type would be Variant (which takes up most memory). Try to save a copy of the table somewhere close by. Try and always pick the variable type that would require the least bytes of memory to be reserved. Remember, the more efficient you use the memory, the faster your application will run.
Scope of variables
We saw that variables are declared with the ‘Dim’-keyword. If you use Dim, a variable will only exist within the procedure in which it was declared. (As an example, if we’d declare a variable within a button-click event, as soon as all code within that event is processed, the variable will cease to exist, and the data inside the variable will be lost).
Hmmm. What if we want to use a variable to store a number for a bit longer? (Think back to our calculator. If the variable would lose it’s data after the click event was processed, we wouldn’t have much use for it, would we?). Well, it’s possible to declare a variable that is created right when the program starts, and will exist as long as the program is running. A variable like that is called a static variable. That kind of variable is declared by using the ‘Static’ keyword:
Static strInput as String
This variable will remain active within the procedure it’s created in (Again, a single click -event for example). Lastly, it is also possible to declare a variable that’s valid for the whole application. Those are called public variables, and are accessible from anywhere within the application. They’re declared with the Public keyword:
Public strInput as String
A Public variable can only be declared at the top-level of the code (Under ‘Option Explicit’). If you try and use it anywhere else (for example within a click-event) you will receive an error if you try to run the application. Same as with picking the right variable-type, always pick the most limited scope. This prevents memory from being used unnecessary, and mistakes from happening.
Constants
Well, as we know now, variables are used for temporarily storing data. What though if we would have a variable that stays the same within the entire lifespan of the application, and is used all-through the application? (Think of a filename that is not going to change within the program, and on which multiple procedures rely). Well, this is also possible. We can use a specific type of variable called a Constant to achieve exactly this.
A constant is declare like so:
Const cstrFilename As String = “C:\autoexec.bat”
As you see, we immediately assign the value of the constant to it. This is because the value will be constant. It will not change. The c is to show this is a Constant. This makes it easier for you to recognise the Constant within the application.