This tutorial will instruct you on the creation of variables in Visual Basic 6, as well as variable types. This lesson requires a very basic understanding of the interface in Visual Basic 6.
Setting Up The Project
In order to start demonstrating the concepts of variables to you, we must first set up a small program where you can experiment with code. This will also be the foundation from which we will build on in following lessons. To start, create a Standard EXE in the same way that you did in the previous lesson. When you are taken to the form designer, double-click anywhere in the blank content of your form. This will bring up the code editor with the following code:
Private Sub Form_Load() End Sub
Take care to remember these last few steps; you will need to do this again every time that you learn a new concept. For now, don't worry what this code means. All that you need to know is that all of the code that you type between these two lines will be executed when your program launches, but before the form becomes visible.
Hello, World!
To test this new concept, enter the following code (in bold) between the two lines:
Private Sub Form_Load() MsgBox "Hello, World!" End Sub
Now press F5 to run your application. This classic program will pop up a dialog box with the message Hello, World! This illustrates how the code between these two lines executes. The line that you entered instructs VB to display a dialog box with the text "Hello, World!" By running the application you can see that, after you click "OK", the default form that was added to your project appears. The details of this are beyond the scope of this lesson, but just know for now that code entered between these two lines executes before the form appears.
What Is A Variable?
Now that you know how to set up a simple project to test code found in these lessons, we can begin with the topic: Variables and Types in VB6. Variables are very similar to their counterparts in mathematics. Variables have a name, such as "x", and hold a value, such as "2".
Box Analogy
A common analogy for variables is a box with a label on it. The box holds content (data) inside of it, such as a number. The label on the box has a name printed on it (identifier). If a person has a room full of these boxes, and knows the name of a specific box, they can find that box and look at the data inside of it. If need be, they could also change the data inside the box before putting it back on the shelf.
Variable Types
So far, you know that variables have a name and hold a value. These are two concepts attributed with variables. There is, however, another concept; types. A variable has a name, content, and a type. A type describes what kind of content will be stored in the box. For example, one box might hold a number, while another box would hold a sentence. Some boxes may only be big enough to hold small numbers, whereas other boxes may be big enough to hold large numbers. The type of a variable governs what content can be stored inside of it.
Creating Variables
When a variable is created within a program, it is said to be "declared". In terms of the box analogy, declaring a variable would be equivalent to placing a new box on the shelf. When declaring a variable, you must give it a name and a type. Based on the type, the variable will automatically be loaded with some default data. Your first variable will be named "x" and will hold a number. Create a new to test code within (described in the previous sections), and add the following code:
Private Sub Form_Load() Dim x As Integer End Sub
Analysis
The previous code consists of 3 lines. We will only take interest in the second line for now. This statement is made up of 4 words. "Dim" stands for "Dimension", and instructs your computer that you would like to create a new variable. "x" is the name of the variable. You must seperate "Dim" and the name of your variable with a space. "As" is an instruction to your computer that you would now like to define the type of the new variable. "Integer" is the name of a type that is built-in to Visual Basic. "As" must be seperated from the variable name and the variable type by a space.
Output
When you launch this program with F5, nothing will appear to happen before the form loads. However, a variable has been created in memory called "x" with a type of "Integer".
Variable Types
The previous example used the "Integer" type to define a variable. This is one of many built-in types in Visual Basic, which are listed here.
Numeric, Integers
The following types will hold a numeric value between two given numbers. They CANNOT hold decimal values (I.E. 3.14).
Numeric, Decimal
The following types will hold a numeric value between two given numbers. They CAN hold decimal values, but only with a certain amount of precision.
Other
Variant Type
When you don't declare a type for your variable, it automatically gets a type of Variant. A Variant is a variable that can hold anything. Visual Basic will make an educated guess based on what you do with the variable first, and change the way that the variable is stored in memory to accomplish the task for you. This sounds like it's a great thing, but it isn't. Variants are extremely slow, since Visual Basic needs to do a lot of work determining how to store it. They also don't work well with many built-in functions. They also have the chance of choosing the wrong type, especially if your code gives the variable values in different ways. The bottom line is simple: don't use Variants unless you have to. Always explicitly declare the types of your variables.
Exercise
Try declaring a variable of a few of the different types listed above. The syntax for a variable declaration is found earlier in the lesson. Remember that the keywords need to be separated by spaces.
Using Variables
Variables would be useless if you couldn't do anything other than declare them. Once you have declared a variable, you can interact with it in many ways. Each of these interactions has their own syntax.
Assigning
To give a variable some new data, you can use the assignment operator ("="). For example, declaring x as an Integer variable and loading it with the value 2 would be accomplished in this way:
Private Sub Form_Load() Dim x As Integer x = 2 End Sub
Note that this is not the same as stating equality, as it would be in mathematics. If you have never used a programming language before, this line may look like it says "x is equal to 2". This is not correct, however, since it is possible to do this:
Private Sub Form_Load() Dim x As Integer x = 2 x = x + 1 End Sub
In mathematics, the line x = x + 1 would not make any sense. This is the trap that you will fall into if you read this line as "x is equal to x plus one". Instead, this line should be read as an assignment, such as "set the value of variable x to the current value of variable x plus one". This works because Visual Basic replaces variable names with their values before assigning a value to whatever is on the left of the assignment operator. Therefore, Visual Basic reads this line as x = 2 + 1.
Displaying
The value inside a variable can be accessed by writing the variable's name in an appropriate position. For example, you could display the value of a variable in much the same way as we displayed "Hello, World!" previously in this lesson:
Private Sub Form_Load() Dim x As Integer x = 2 MsgBox x End Sub
You can use this technique to see what the default value of a variable is by displaying the variable before a value is assigned.
Private Sub Form_Load() Dim x As Integer MsgBox x End Sub
Math
Variables of a numeric type (see the type list above) such as an Integer or Double can have mathematic operations performed on them. To add two variables together, one would use the addition operator ("+"). Likewise, there is also a subtraction operator ("-"), multiplication operator ("*"), and division operator ("/"). These operators are used much like they are in mathematics, with one variable on the left and one variable on the right.
Private Sub Form_Load() Dim a As Integer Dim b As Integer Dim c As Integer a = 5 b = 5 c = a + b MsgBox c End Sub
These do not have to be variables, however; they could just as easily be constant numbers.
Private Sub Form_Load() MsgBox 5 + 5 End Sub
Why Use Variables?
At this point you may be wondering why somebody would use variables instead of always using constants. The answer is quite simple: constants must be constant, while variables can be variable. It is very common in a program to perform an action based on input. In order to do this, the input must be stored somewhere; and that is what variables are used for. You will discover the full power of variables when you learn about functions and how to fill variables based on user input.
Implicit Declaration
Don't be scared off by the title of this section, it's actually a very easy concept. When you reference a variable in your program that doesn't exist, Visual Basic will create the variable for you. For example:
Private Sub Form_Load Dim a As Integer Dim b As Integer a = 5 b = 2 c = a + b MsgBox c End Sub
The previous example will add 2 variables together and display the result. However, it uses a variable called "c" which was never declared. When your program gets to this line, a variable called c will automatically be created for you with a Variant type (a bad thing). This also brings another problem: typos. What if you misspell the name of a variable? The following listing demonstrates this common bug.
Private Sub Form_Load Dim There As Integer There = 2 Dim Who As Integer Who = 5 Dim What As Integer What = Who * 3 Dim Why As Integer Why = What / There Dim When As Integer When = Why * Who What = 3 Their = What + When MsgBox There End Sub
This program is intentionally bloated and complicated. Several variables are declared and modified, and at the end, the value is assigned to the first variable. When the variable is displayed however, it is unchanged... it retains it's value of 2 from the start of the program. This is because the variable was misspelled as "Their" near the end of the listing. Visual Basic automatically created a Variant variable called "Their", but since the variable is spelled correctly later on, it is magically unchanged. This mistake may be obvious in such a small program, but imagine a large program with hundreds of thousands of lines of code. If a variable was misspelled in one obscure part of the program, it would be nearly impossible to track down the bug when the program began behaving oddly.
Protecting Yourself
Luckily, it is extremely easy to protect yourself against this feature-- turning it off! You can turn off this feature by typing "Option Explicit" at the top of your program.
Option Explicit Private Sub Form_Load Dim There As Integer There = 2 Dim Who As Integer Who = 5 Dim What As Integer What = Who * 3 Dim Why As Integer Why = What / There Dim When As Integer When = Why * Who What = 3 Their = What + When MsgBox There End Sub
This listing is identical to the last one, except with "Option Explicit" at the top. The typo is immediately flagged by Visual Basic when you try to run this program. Visual Basic will display a message box on the screen that says "Variable not defined" and it will highlight the location of the undefined variable in your code so you know exactly where it is. This is why you should always have this at the top of your code.
Since option explicit is really the only way to program, Microsoft has given you a preference in the VB IDE where you can tell it to automatically add option explicit to your code. I highly recommend setting this by going to the menu bar at the top of the screen and selecting Tools -> Options. On the first tab (Editor) you will notice a check box that says Require Variable Declaration. Check this box and from then on VB will put Option Explicit on top of all your programs.
Great Tutorial
I've created a simple calculator by the help of this tutorial.
hi
How to display msg box with message and value?
Pls reply!!!
Concatenate the string of
Concatenate the string of the msg box with the value using "&" operator ... like this
Dim variable as Integer
variable = 4
Msgbox "Some kind of message , value : " & variable
'the output will be message box with text "Some kind of message , value : 4"
MsgBox with text and value
If you want to display a message with a stored value from a variable from your code or a text from a control, use the following code:
MsgBox "Here is a number: " & your_variable
or
MsgBox "Here is a text: " & Text1.Text
how to assign text in textbox as a variable?
ex:
you have to add to numbers from the textbox.
ive tried this:
dim num1 as integer
dim num2 as integer
num1 = text1.text
num2 = text2.text
when i play it.. it selects the "text1" and says: compile error: invalid outside procedure.
PLS HELP :) tnx
It should be like this
It should be like this num1=txtnum1.text fo r all of assigns
Try like
Try like this!
text1.text=num1
text2.text=num2
RE: how to assign text in textbox as a variable?
Please post your code.
tobz
Plz correct:p
in line no 20 of last code the final value should bassigned to 'there' instead of 'their'..
You r doin' grt job...
ya! Right..
ya! Right..
to make a word bold in message box
can any one help me to make a word bold in message box.
eg "Hai Good Morning". I need to make bold only "Good Morning"
Great Tutorial
Thanks :)
Learned stuff I've never completely understood and in this c++ language that I'm new to.
@Anonymous - Thu, 10/16/2008
@Anonymous - Thu, 10/16/2008 - 14:30 (1st poster) - dingbat, that is the whole code.. :P
NO HELP
USE SOME EXAMPLES LIKE WRITE THE WHOLE CODE OUT INSTEAD OF BITS AND PIECES
i need help about getting values from 2 forms..
i need help about getting values from 2 forms..
i have to get the subtotal price in form 1,and the subtotal price in form 2
and then compute the total price in form 3..
how can i retreive the 2 values of different forms to sum it up on the last form???
i am almost done with my work.. =) thanks to anyone who can help me..
Did u get it?
I need to do something similar... In form1 I have an array to save information [name = n(x), age = e(x), sex = s(x), etc], and in form2 I have to do a list with this info. I know how to do lists, but I need values from form1 to use them in form2... how can i do that?
My mail is mysthique@gmail.com... If someone can help me before this sunday 11, I'll love him/her forever... if it happens after sunday, i'll be very very happy :P
My english sucks xD
Sorry if this is a little
Sorry if this is a little late, I saw the dates on the posts, but I figured I'd leave my mark for anyone else who needs help. What you'd do in this situation is dim the variables globally. For more info, just look up how to dim variables globally.
Learned alot
Hey nice man. I learned alot and my head didnt hurt. :)
Nice Tutorial
May have to get you to come work for me
Post new comment