Home and Learn: VB Net Course

An Introduction to Functions and Subs

So far, the code you have been writing in these tutorials has mostly been lumped together under one button. The problem with this approach is that your code can get quite long and complex, making it difficult to read, and difficult to put right if something goes wrong. Another approach is to separate some of this code into its own routine. This is where functions and subs come in.


Segements of Code to do a Particular Job

The two terms refer to segments of code that are separate from your main code. You've already met some string functions - Equals() and Substring(), for example. These functions are built into Visual Basic. But if you could see under the hood, what you'd find is some code to do these jobs for you. All you have to do is to specify, for the Substring() function, what the string is, where you want to start, and how many characters you want to grab. You don't have to worry about how Visual Basic gets your answer, because the code is all wrapped up in a function, ready for you to use over and over again.

And that's the point about Functions and Subs: it's code that you might want to use over and over again. You don't have to keep writing the same code every time you want a specific job doing. Just write the code once, and then when you want to use it, just let Visual Basic know.


Write a Function or Sub to do the Job

Think about error checking when people are entering data on your Forms. You'd probably have a lot of Text Boxes, and want to check that the user was entering the correct data. You don't want people entering numbers in your First Name text box, for instance. To check that the user has entered the correct data, you write some error checking code. Except you might have lots of text boxes on the form. If you want to check all the text boxes, you'd have to write the same "checking" code for each text box. Instead of doing that, you can write your own Function or Sub. You only have to write it once. Then when you want to use it, you just refer to it by name, and the code will get executed. We'll soon write a Sub that we can use over and over again.


The difference between Functions and Subs

First, though, in case you are wondering what the difference is between a Function and a Sub, it's this: Functions return a value, and Subs don't.

Substring() is a Function, because you want some sort of answer back, and an answer that you can then use elsewhere. You assign the answer to the Substring() function to a variable.

A Sub is some code or job that you want VB to get on with and execute. An example is closing a form down and unloading it with Me.Close(). You don't need to return a value, here; you just want VB to close your form down.

An example or two might help to clear things up. We'll start that on the next page.

Back to the VB NET Contents Page


Buy the Book of this Course

Email us: enquiry at homeandlearn.co.uk