Understanding variables

Level:
Level1

In the previous tutorial (Visual Basic 6 Beginner Tutorial - Hello World) we learned how to create a program that when the button is clicked a message box says "Hello, World". Now we will build upon that program to learn how variables work in Visual Basic.

A variable in a programming language is similar to the way a variable works in math. If I have the equation x = 2 + y, I have two variables - x and y. These variables represent any number that can be placed in them. In the programming realm, we define a variable by a given name (for example var1) than var1 can store a value and later when we want to use that value we can call it up by its name. It makes a lot of sense once you see a few simple examples.

In Visual Basic we define a variable name by using the keyword Dim. Dim stands for "dimension" - which is a carry over from early programming days. When you define a variable, you also specify what type of data it is allowed to hold. Below is a list of all the different data types and what data they can hold.

TYPE Can Hold
Boolean True or False
Byte A number 0 to 255
Double A 64 bit floating point number (I.E. 3.1415) - This is used when a high degree of accuracy is needed.
Integer A whole number from -32768 to 32767
Long A whole number from -2,147,483,648 to 2,147,483,647
Single A 32 bit number like a double, but with less pecision
String A collection of letters such as "Hello". This is used to store words and sentances.

These are the main data types built into Visual Basic, along with these are a bunch of classes Microsoft created for us to use such as Currency, Date, Time, etc. You can even create your own data types - more on this in another tutorial. There is also one other data type that is very unique. It is called the Variant type. This data type can hold any of the data above. You might immedatly ask then why don't we just always use the Variant type? The main reason is size. Variants take up more memory than any of the other data types listed above. So if you know your variable is going to be storing specific data, declare it in a way that uses the least amount of memory by specifying the type above. Usually we know what our variable will hold so we shouldn't have to use the variant type very often.

So lets take our Hello World example from before and now lets use a variable. Here is the code from before: 

Private Sub Command1_Click()
   MsgBox "Hello, World!"
End Sub

Now lets add a couple of lines and change our MsgBox function call to match this code: 

Private Sub Command1_Click()
   Dim var1 As String
   var1 = "Hello, World!"
   MsgBox var1
End Sub

So lets go through this line by line. The first line the Visual Basic environment created for us - leav it be. Line 2 declares a variable named var1 as a string type. This means our variable can only hold strings (which are a collection of letters). Line 3 assigns the string "Hello, World!" to the variable var1. Notice that we put double quotes around the string Hello, World! this tells VB that this is a string and not some key words or other variable names. You always wrap a string in quotes.

Now that var1 contains our string we can use it in place of that string. For example the MsgBox function takes as its parameter a string. It will then display that string for us in a message box. If you remember before we called the function like this: MsgBox "Hello, World!". Now instead of doing that if you look at line 4 we simply tell MsgBox to display the string stored in var1. Lastly line 5 was created for us by the VB design environment leave it be as well.

If you now press F5 to run the program and click the command button you will see "Hello, World!" displayed in the message box once again.

Visual Basic Tutorial Screen 6

A Note On Automatic Variable Declaration

Visual Basic will do something very fancy for you. It is also very annoying. If you assign a variable a value and don't declare it (using the Dim statement) visual basic will declare it for you behind the scenes as a variant. The first annoying thing about this is that the variable is a variant, and as we learned earlier this is not very efficient. But an even bigger problem exists as you develop more and more advanced programs. Let me demonstrate this in an example.

Lets say you write the above code like this:

Private Sub Command1_Click()
   var1 = "Hello, World!"
   MsgBox var1
End Sub

Line 2 of this code assigns a value to var1 (a variable that has not been declared). Visual Basic will declare the variable behind the scene as a variant. Then when in Line 3 we call MsgBox with that variable it works great. If you run this program it will work just like before, and Hello, World will be displayed. Everything seems great, but lets say we make a mistake like this code has done:

Private Sub Command1_Click()
   var1 = "Hello, World!"
   MsgBox var2
End Sub

If you notice I accidentally told the MsgBox to display a variable named var2 instead of var1. Now this is absurd because I don't even have a variable named var2. Now what I would expect to have happen is that when I run this program, an error message would pop up that says there is no such thing as var2 and tell me what line this error occured. Than I would go to that line see the mistake I made and change var2 to var1. However, since VB automatically creates variables for me it instead will create a variable named var2 and it will have no value assigned to it. So the result is a message box that says nothing.

Visual Basic Tutorial Screen 7

 

Now imagine my program is thousands of lines of code long. I run it and click on the button and this message box with nothing in it shows up. Now I am stuck going through all my code trying to figure out where I used a variable name that is incorrect. This is a very annoying feature indeed. Because of this any Visual Basic programmer that is worth his weight in salt will put the Option Explicit clause at the top of all their programs. This tells Visual Basic that you will always explicitly declare your variables. Than if VB finds a variable that was not declared it will throw an error so you can easily discover it and fix it. Here is what our code looks like with this line added:

Option Explicit
Private Sub Command1_Click()
   Dim var1 As String
   var1 = "Hello, World!"
   MsgBox var2
End Sub

Now if you again run the program - it will throw an error telling you the variable is not defined.

Visual Basic Tutorial Screen 8

And it will go to the line where var2 is located and highlight it for you. You can than fix it by changing var2 to var1, hit F5, and the program will work as planned.

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.

Visual Basic Tutorial Screen 9

If you enjoyed this post, subscribe for updates (it's free)

Can I dimension variables in a For loop?

Any idea how I might accomplish the following:

I'm trying to allow a user to specify a number of items which I will then concatinate into a string that I can use to create a new variable to hold an integer value.

If the user enters "6" for a value in a variable "usernum", I try to run it through a For loop as follows:

For i = 1 to usernum
mystr = "item" & cstr(i) -- this gives me "item1", "item2", "item3", etc.
dim mystr as integer
i = i + 1
Next i

Simple, or so I thought. When I try to dimension"mystr", I get errors about it being variable.
I've tried to place the string value contained in "mystr" into a text box and tried the following without
success:

dim text1.text as integer
dim str(text1.text) as integer
dim cstr(text1.text) as integer
dim value(text1.text) as integer

Is there a way to do this? I didn't want to get overly complex for something that seemed relatively
simple but if there is no other way I suppose I may have to.

Thanks for your help.

Can I dimension variables in a For loop?

Any idea how I might accomplish the following:

I'm trying to allow a user to specify a number of items which I will then concatinate into a string that I can use to create a new variable to hold an integer value.

If the user enters "6" for a value in a variable "usernum", I try to run it through a For loop as follows:

For i = 1 to usernum
mystr = "item" & cstr(i) -- this gives me "item1", "item2", "item3", etc.
dim mystr as integer
i = i + 1
Next i

Simple, or so I thought. When I try to dimension "mystr", I get errors about it being variable.
I've tried to place the string value contained in "mystr" into a text box and tried the following without success:

dim text1.text as integer
dim str(text1.text) as integer
dim cstr(text1.text) as integer
dim value(text1.text) as integer

Is there a way to do this? I didn't want to get overly complex for something that seemed relatively simple but if there is no other way I suppose I may have to.

Thanks for your help.

Thanks a lot

Hi team,
Thanks a lot for the information above, i went for VB class seperately but I was not sure about what is Option Explicit and why do we need it. But now Your tutorial has explained me the concept quite very well. Thank you once again:)

I'm a beginner to VB

Thank you very much for the tutorials. Very easy to understand.

Awesome

The site is laying a good foundation for me. I LOVE IT

Comment

I thanks to the editor of this tutorial, because it helped me in very easy and fast way. thanks again...

Yeah

Again this is nice!

thanks

great tutorials froms great guys in a great site
many thanks ^^

Perfect

You guys made a great job, thx.

Really helpful! The best VB6

Really helpful! The best VB6 website...Thanx!

Is there a simply guide

Is there a simply guide elsewhere besides this site?

Really great job

I bought a lot of books and read a lot of articles on internet. BUT, what i found in this site is magnifique, absolutely extraordinary job you made over here. I am speachless. Best way to explain, describe, help, explanations....... really great job people

Regards and Best wishes,
Kti

IMPORTANT HELP NEEDED

Can someone please help i have a school project and my code isnt working, can someone show me a line of code that will work.
I need to use number values from 3 or more variables, get them to add/multiply/divide together and then put that result into another variable of a different name.

All suggestgens will be greatly helpful!!!!!!!!!!!!!!!

!!!!!!!!!!!!!!!! Jay666 !!!!!!!!!!!!!!

very nice indeed

very nice indeed

Visual basic

Hi guys it is nice.
i want built a software for pay bill in visual basic can any one help me?

Great place to learn VB Basics

Hi I am new to VB.I was worked as an Apps Tech Consultant.
Recently we got a project in which we have to work on VB6.0. I found so many websites. But here we can learn very easily and effectively. Great job by the team..

I appriciate every one who worked in this.

Thanks,
Suri

Wow!Ahsante sana!

I'm a VB trainee at the moment and I have come across this site for tutorials, I real like it guys, It is helpful to my study!
I hope I will be back more often!

Excelent guide

Even though I have allready learnt all this before I must say that this is a great guide. 5/5. If I didn't know this before, I would no doubt understand it after :)

Understanding (VB6) variables tutorial

This is a great tutorial cearly put. I have learnt VB before but i have understood better in this tutorial.

Excellent site

Ireally appreciate your good works .This site is of great help to those who are keen to learn VB easily .What i like about this site is ,it explains yhe stages in simple english .So even u are in any field you can learn Vb online without any hassles

Understanding Variables

Very good tutorial.
I've gone through a half dozen tutorials on this site and all have been very good.

A way back when, I learned non-visual interpreted BASIC on a 6809 (8 bit processor) based system.
RAM memory was expensive and conserved, so the DIM statement was very useful.

The BASIC manual I learned from, presented DIM as short for Designate In Memory.

This is not my definition, so I won't defned it; it's just what I read.

Need Help plz

I was just wondering how you would create a label where there are several parts to it. For example im pretty sure the code looks like:
" hello " & " hi ".....
but i have no idea how to make it work and btw nice tut.

Not to be nit picky

Not to be nit picky but......
All the while I was reading all that, I was wondering what dim stands for? So I googled it and it stands for dimension.
Would have been nice if you provided a little about about how that statement works behind the scenes.
(not that it just declares variables)

Otherwise great guides so far!

History of Dim Statement for

History of Dim Statement for post above

Here is a bit of history I found on the dim statement
"The book mentions that DIM is short for Dimension. This goes wa-a-a-y back to the earliest days of Basic (before "Visual" Basic). In fact, it goes back to the even earlier language Fortran. So, although you might think using a word like DIM isn't too bright (pun intended), it's used because there is just too much history now to change it."

Had it originated in Fortran??

History of the DIM statement in VB

This is basically what happened. The BASIC language used not have feature for declaring variables. You just start using the variables

X = 5
Y = X + 6
PRINT Y

Declaration wasn't deemed strictly necessary. However, when it came to arrays, for performance and simplicity, you need to specify the size of the array ahead of time. Hence, the Dim statement:

Dim V(10)

V(1) = 9
V(2) = V(1) - 7
etc.

So for years (probably 15 years), BASIC was used this way, and no one considered DIM to mean anything other than DIMENSION, because that's what you're doing here: you're specifying the number of dimensions for the array. You could have said:
Dim V(10, 50)

In the 80s, when Microsoft enhanced Microsoft Basic, they added the ability to declare a variable. Rather than come up with a new keyword, such as Var or Declare, they decided to reuse an already existing keyword, Dim. This was customary at the time as to not introduce new symbols and break existing code. After all, if Var now became a reserved word, you can't call a variable your variables Var. What if existing code used that symbol for a variable name.

ty

ty

nice info

thanks

really help ful

This class is really helpful to me.

I'm only 16 but I have very

I'm only 16 but I have very much experience in programming C++ and C and this is better than the professional guides for those :D

Get your thens and thans

Get your thens and thans straight

thanku very much, u r really

thanku very much, u r really doin a great job in teaching vb to beginners n professionals.

Cool

hey..this is great work done...i've been reading abt variables and declarations for a long time, but your work made it so easy that i think all my queries have been addressed..keep it up.

Ash

Comments

Excellent Tutorials. I am new to VB and this has helped me do a lot within a couple of weeks. Would recommend this site to anyone and all for VB. I strongly recommend this as a 'Must See site'.

Once again Great work and thanks to all who put it in together.

Regards

Joji

Simply great approach!

Hi, you guys are great. I've never seen such a clear straight forward vb tutorial like what you're providing us.

Thanks and apparently, I'm learning.

Godspeed!

Ochie (Philippines)

WOW

couldnt have put it better myself (becuase i didnt know this till i read it. lol!)

Understanding variables

Hey. I like your style.
I'm a relatively new DBA, having late in life discovered this talent and affinity.
I inherited a broken Access DB where front end is not communicating well with its back end.
(Hmmm ... sounds like me come to think of it.)
It's a custom-designed application about 15 years old and has gone through several application and version conversions and upgrades (dBase to FoxPro? to Access 95, 97, 2000, 2002/3, so some of the old VBA code has developed gremlins and glitches. Problem is I don't know squat about VBA. I don't know squat about ANY programming language except Fortran, that I learned in my one and only Comp Sci 101 course many, many moons ago.

Anyway, I just came across your tutorial site, and I like what I see. I'LL BE BACK.

Best regards, - Ben (bway79@msn.com)

a question

umm int his tutorial it was said tat if u click the require variable declaration in option .. VB wud put option explicit on every program .. well i checked this option n then removed option explicit from my form whr i implicitly rote it ... n then wen i compiled the program .. VB compiled it .. whereas if i understand correctly .. it shud giv an error ...... can any1 tell y

Great TuT

Great Job!!

nice

nice

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. The supported tag styles are: <foo>, [foo].

More information about formatting options

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.