Back to article

Visual Basic Tutorial - Part 4

November 4, 2002

Welcome to the fourth instalment of our Visual Basic tutorial. We're pulling out all the nerdy stops and throwing geek-speak out of the window. We're here to make Visual Basic easy!

If you haven't read any of the previous tutorials, grab part one, part two and part three.

Anyway, enough of that. For all those with memories the size of my little toe, allow me to introduce myself once more. I'm Karl Moore, a technology journalist from bonny England. I'm smooth, suave, sophisticated and cunningly handsome. But hey, I don't like to blow my own trumpet. I'm just letting you know I have a trumpet.

But enough patter, it's time to program! This week, we're going to start nice and easy with a word about looping and grabbing information from users. Then we're going to get really serious by creating our own "subs". And when you can master those, you're a PRO, baby!

Don't look at me, but there's a loop on the loose. In this section, we're going to look at two things - firstly, how to create a "loop" in code and secondly, how to get information from the user.

Karl explain loops!

Loops are amazingly useful. For instance, you may want to display a message box for every single student in your highly successful grammar school. You can do this two ways - either manually code every single message box (highly inefficient, goes against all coding practices and not very tech-savvy) or use a loop that says, in English, "display a message box for every student".

Creating a loop is pretty simple. Let's look at a sample piece of code

For i = 1 to 5Msgbox "I have looped round " & i & " times"Next i

I'll explain what's happening here.

The first line tells Visual Basic how many times it should loop around. It's saying - loop around this bit of code five times and store the number of times it has looped around in "i". The second line is just a simple message box we display that shows "i" - don't forget, "i" is just the number of times it has looped around. The third line, "Next i" just tells it to go back to the beginning until it's gone from one to five.

Phew! That's a lot to take in. But don't worry - you can do it!

Just think of what you could use this for! You could say to Visual Basic - loop through all the students in our school database and add them to a box on the screen.

I bet you thought that was it with loops, eh? No such luck.

So you thought there was only one type of loop, eh?

"Do Until"

Loops come in many different flavours. The one I just demonstrated was a pretty simple (Reader: What!?) loop - you tell it how many times to do something - and it does it!

However they can get a little more complicated. You may want to keep asking a user for a student name until they type in "END" or something.

We can do that with a "Do Until" loop. Let's take a peek at some sample code-

Dim UserInput as StringDo Until UserInput = "END"UserInput = InputBox("Enter the student name, or type END to finish:")Msgbox "You entered student - " & UserInputLoop

OK, you're probably wondering what I'm blabbling on about here. Don't worry - I tend to get all geeky every now and then. Just humour me.

The first line merely declares a variable called "UserInput" to hold a string (aka plain text). Remember we talked about variables in the last tutorial? We're just telling VB we want to store some text in a thing called "UserInput".

The second line tells Visual Basic to loop around until the "UserInput" variable is equal to "END".

The third line introduces a really neat function weve not talked about yet. It's called the InputBox and is just a cool way of getting information from the user.

When you run this, a little box will appear for the user to enter some information - in this case, a student name. Whatever they enter will be assigned to "UserInput".

Once again, we're just saying the UserInput variable should equal whatever the user puts in that InputBox.

And the fourth line just says- loop back to the start again. And at the start, Visual Basic asks the question once more - does UserInput equal "END"? If it does, then I'm going to stop looping around. If not - I'm going to carry on!

Get it? Got it! Good!

Have you noticed the bug yet? When you enter "END" in the InputBox, it displays the message "You entered student - END". If you're feeling confident, try writing an If-Then statement as discussed in previous tutorials to avoid this occurring.

Creating a practical project.

Before you continue, I'd like to set you a little task. Try doing this - create a form and add a command button ("cmdStudentEntry") and list box ("lstStudents"). In the code behind the command button, prompt the user "How many students do you want to add?" - and then displays that number of input boxes to accept student names, adding each to the list box.

Now don't read below before you attempt the task. Oooh, I know it's tempting. But don't. No! NO!! Stop it. Stop right there, sonny. I've been around the world a bit and have got your number. Nudge, nudge, wink, wink. Ooh la la, folly de lay! Yah, boo, sucks to you.

Confused? You will be. Here's the code you need to add behind the specified command button:

Dim NoOfLoops as IntegerDim StudentName as String' Dim a couple of variables to hold informationNoOfLoops = InputBox("How many students do you want to add?")' Ask user how many times to loop aroundFor i = 1 to NoOfLoops' Tell Visual Basic how many times to loopStudentName = InputBox("Enter a student name:")' Put student name into StudentName variablelstStudents.AddItem (StudentName)' Add the name stored in StudentName to the list boxNext i

Sorry folks, but this is where it gets serious. Put away your Beano annual and get out Programmers Weekly. In this section, we're going to explain Subs.

What are subs, and how are can they help VB coders simplify their source?

Corny jokes to one side, these things are really useful. And pretty darn simple when you get the hang of it.

In preparation for this article, I found the word in my Thesaurus. Its alternate suggestions included "inferior", "assistant" and "helper" - the latter of which probably best defines the term.

A Sub is basically a piece of code separate from the rest. It's often used when you have a piece of common code that you don't want to rewrite each time you use it.

Let's pretend I'm Bill Gates (imagine the salary!). I helped created Microsoft Word. How does a user exit Word? They can either click on the top-right hand Close button ( ) or press the Exit button.

What if each time they exited, I wanted to say "Thanks for using Office and adding another $500 bucks to my wallet!"?

Well, I'd have to duplicate code.

Each time the user clicks on that corner cross button, the QueryUnload event of the form fires up. So, I'd write my code there.

Then, if the user click on my Exit button, I'd have to write the code in the command button's Click event. Phew!

And what if I had an Exit option on my menu, too? You can see the problem here, folks. Duplication of code leads to huge maintenance issues - particularly if you're not just dealing with simple message boxes. Every time the user logs out of your program, you may want to record the time and date in your security log. You wouldn't want to duplicate all that code, would you?

You can get around this using Subs. You can create a singular, generic chunk of code that displays the message and then ends your program.

Therefore, in the QueryUnload event of the form and the Click event of the command button, you simply need to tell Visual Basic - "Run the code behind that Sub!"

Let's try this one. Create a Standard Exe, with a form and command button. Open the code window and change the Object drop-down list to (General). Now type-

Sub EndProgram

and press enter. Visual Basic should add "End Sub" to your code. Your screen should look something like this:

Sub EndProgram()End Sub

You've just told Visual Basic you're creating a Sub called "EndProgram" and have defined the appropriate code boundaries. Now you need to write code inside that Sub.

Type in -

MsgBox "Thanks for using my program. Have a really super day, geek!"End

Great! You've just defined your own Sub called "EndProgram" and have written code within it. Now each time we run EndProgram, it will display the insulting message and end your application.

But how do we get it to run? Simple.

Firstly, we'll tell it to run the Sub whenever the QueryUnload event of the form occurs.

In the code window, change the Object drop-down list to Form and the Procedure drop-down list to QueryUnload. In the code that appears, type the name "EndProgram".

Your code should look something like this:

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)EndProgramEnd Sub

Now add the same code to your command button - and try running your application.

Whenever you click the command button or try closing the form, Visual Basic runs your Sub and processes the code within it.

The ability to create such Subs can be a real time saver! It avoids unnecessary code and therefore cuts down on the size of your final program. It also saves on boring maintenance time.

Everything going well? Understand it all so far? Oh good - 'cause I'm about to throw a massive spanner into the works. You see, sometimes simple Subs just aren't clever enough.

Are standard subs too simple?

A more advanced form of procedure...

For instance, say you were creating an insurance quote system where you need to pass information to the Sub - say, the premium to pay each year. Then the Sub needs to multiply the premium by two and display the information in a message box.

Following me? Good. Create a new Standard Exe with a simple form and two text boxes and command buttons as such:

Call them txtCalcOne, txtCalcTwo, cmdCalcOne and cmdCalcTwo respectively.

Open your code window once more and select (General) from the Object drop-down list. Now type -

Sub CalculateAmount(Amount as Integer)

and press enter. Then tap in the following code:

MsgBox Amount & " times two equals " & Amount * 2

Your Sub should look something like this:

Sub CalculateAmount(Amount)MsgBox Amount & " times two equals " & Amount * 2End Sub

This is getting weird now, so let me explain.

If you can remember doing maths at school, you'll probably recall that most fashionable of topics, algebra. Well, it's back in fashion.

With this code, we're telling Visual Basic that when we call "CalculateAmount" in the future, we'll also be passing it a parameter called "Amount" - the value of which we are currently unaware.

In the code, our Sub refers to this "Amount" - even though its value isn't currently known. The code displays the "Amount" in a message box - as well as multiplying the number by two with the code, "Amount * 2".

We've not talked about calculating in Visual Basic yet, but it's pretty straightforward. The calculation operators are determined by the following keys

  • Multiplication *
  • Addition +
  • Minus -
  • Division /

So if you wanted to add 5 and 7 together, then divide the result by 10 - you could program "(5+7)/10". If you've ever used Microsoft Excel, you'll know all of this.

What did you say? Shut up and get on with the tutorial? Oh. Yes, right. Fine. No problem. Don't worry over me. Lil' old me. That's fine.

Let's imagine we called our Sub and passed it the number four. It would take that "Amount" and display a box that should say something like:

"4 times two equals 8"

To calculate the 8, VB simply multiplies the value of "Amount" by two.

Let's add the code to call this Sub. Under the Click event of cmdCalcOne, add the code:


We're now calling the CalculateAmount Sub, passing it the text value of txtCalcOne as "Amount". If it's a number, it will calculate the appropriate figure.

In the Click event of cmdCalcTwo, add the code:


Notice that we're now passing a different value to the Sub - that of our second text box.

Try running the application, entering various numbers into the text boxes and clicking their associated buttons.

If you don't enter a valid number into the boxes, be sure to expect errors. Don't say I didn't warn you! If you get errors such as "Type Mismatch" just hit the End button and start again. It's just warning you it can't calculate because you didn't enter a proper number.

Are you starting to see the value of Subs, particularly Subs with parameters? You pass this general piece of code a value that it utilises in code.

Perhaps you could use it to change the caption of your form, depending on the customer name. Perhaps you could use that one piece of code to disable or enable all the command buttons on your screen. Perhaps you could just forget about Visual Basic and go back to farming. It's your call.

Karl concludes this week's epic article.

This week, we've taken a geek peek at the wonderful world of darn useful Subs. And parameters. And mathematical operators. And loops. And.... whew! I need a rest.

But if you're still raring to go, here's a little homework. Try finding out how you can add another form to your Visual Basic project. It's something we haven't touched on, but have a go. Create one form with a command button that opens a second form. Let me know how you get on!

In the next tutorial, we'll be reviewing properties, methods and events in an organised, civilised, stabilised, randomised fashion. Then we'll be confusing the whole issue with talk of Functions. These are basically Subs with frills.

And you know, it took me an absolute age to understand the concept behind functions - as no programmer could explain it in English. Join me in part five to see if I succeed...

Until then, this is your smashingly groovy host, Karl Moore, saying goodnight for tonight. Goodnight!

Karl's Visual Basic Tutorial Index

Visual Basic Tutorial
Visual Basic can be confusing, especially for newbie programmers. But don't worry - here to help is technology journalist and head geek Karl Moore, with the first installation of his up-and-coming Visual Basic tutorial!

Visual Basic Tutorial - Part 2
Karl Moore returns with the third instalment of our exclusive no-geek-speak Visual Basic tutorial. This week, Karl gets his hands dirty with variables and conditional logic, so get out your nerds dictionary!

Visual Basic Tutorial - Part 3
Karl Moore returns with the third instalment of our exclusive no-geek-speak Visual Basic tutorial. This week, Karl gets his hands dirty with variables and conditional logic, so get out your nerds dictionary!

Visual Basic Tutorial - Part 4
Karl Moore gives you the buzz about looping, grabbing information from users and subs, as always without geek-speak!

Visual Basic Tutorial - Part 5
Karl Moore returns with another geek-speak free guide to Visual Basic coding. This week, Karl explains what methods, events and properties actually are, as well as delving into the enigmas that are functions. Lets code geek-to-geek baby!

Visual Basic Tutorial - Part 6
Head geek Karl Moore returns with the final instalment of his popular jargon-free VB tutorial!

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date