Microsoft & .NETVisual BasicVisual Basic Tutorial - Part 3

Visual Basic Tutorial – Part 3

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Welcome to the third instalment of our exclusive VB-World.net tutorial!

Every week we get our hands dirty with Visual Basic, showing you the digital ropes to success without getting bogged down in geek speak.

Don’t forget that I love to hear feedback. If you think I’m boring, use the response form on the last page of this tutorial. If you think I’m great, use the response form on the last page of this tutorial. If you want a date, e-mail me. ;-))

If you haven’t checked out any of our previous tutorials, surf down to part one or part two.

So far, we’ve covered Forms, controls, events, properties and some basic coding. This week we’ll be taking it a step further. Get out your nerds dictionary as we define variables and play in wonderful world of conditional logic!

Get it? Very Able? Variable? Hahaha! Oh gawsh, I’m so funny. Please, stop laughing. No autographs, thanks. Sheesh, I should be working on Comedy Central or something.

What are variables, and how can they be used in your Visual Basic apps?

Anyway, I’m not, so back to the content.

Variables can be thought of as invisible Text Boxes, the values of which can be changed with a single line of code. They’re just something you hold information in.

For example, let’s pretend you wanted to display a number every time the user clicks a Command Button. That’s pretty easy. But what if we wanted to automatically increment that number with each click? Hmm, that’s where variables can help out. Let’s code!

  • Launch Visual Basic and create a new Standard Exe
  • Add a Command Button to your Form
  • Change the button’s Name property to "cmdVariableCount" and its Caption property to "Click Me Quick!"

Then:

  • Double click on a blank area of the Form to open the code window

Near the top of the code window, you’ll notice two drop-down boxes. The first specifies an object, the second a procedure. In English, these are defined as:

Object – the thing you want to work with, say cmdVariableCount

Procedure – denotes the ‘event’ for which you want to write code. For instance, we may write code in the Click event to have it respond when the user clicks on cmdVariableCount. Other cmdVariableCount events include GotFocus and MouseMove. The Procedure drop-down can also display user-defined Subs and Functions, which we’ll cover in a later tutorial

In two twitches of a ducks whisker (Ed: In English we say "In a minute") we’ll be entering code that responds to the Click event of cmdVariableCount. But first, I’d like to introduce you to a special bit of the code window.

  • Click on the object drop-down box, the first one

You should see a list of objects – probably Form, cmdVariableCount and (General). The first two are objects – and you can add code to respond to their events. For instance, you may make a message box appear when someone clicks on cmdVariableCount. Or maybe play a tune when someone opens the form. Or whatever.

But you’re probably scratching your head over the latter item, (General). If so, don’t – firstly, because I’m about to explain it and secondly, ’cause knits don’t appreciate such random attacks.

(Ed: Oh boy, hits have just fallen by 50%!!)

(Karl: And if you were scratching your head, 50% of knits will have just fallen, too!)

  • Select the (General) section from the drop-down list

The right-hand combo box should change to (Declarations).

You’ll notice that your cursor isn’t surrounded by any code as with usual event procedures, such as "Public Sub cmdVariableCount_Click()". That’s because you’ve reached a special place in your code window – the top – where you can create, or "declare" variables.

To declare a variable you use the syntax:

Dim MyVariable as DataType

…where MyVariable is the name of your variable and DataType is the type of information it should hold. Don’t forget that a variable is just a non-visible holding place for a value. Here’s a short list of the most common DataType values:

String – If you’re going to store text in the variable

Integer – Used when storing a number

Boolean – Used when storing a True/False value

Date – Used when story a date value

That’s enough theory. Let’s declare our own variable in code!

Decoding declarations…

Are your whites whiter than white itself? If so, you’re undoubtedly colour blind.

Are you aged between 22 and 22.5 and looking for a date? If so, e-mail me.

Are you in the (Declarations) section of the (General) thingy? If so, read on.

It’s now time to get serious and declare our own variable.

  • Type in:
Dim CountClick as Integer

I’ll explain what we just did. In the General Declarations section of your code window (the top bit), we created or "declared" something called CountClick. When our program runs, it creates a ‘variable’ called CountClick to hold a value of the Integer type – also known as a number.

Don’t forget – a variable is just something in which we can store a certain type of information.

Let’s test the variable by adding some code to the Command Button we created.

  • From the code window, select "cmdVariableCount" from the object drop-down box and ensure the procedure box reads "Click"

If so, that’s great! If not, check your screen resolution. Visual Basic should create the following for you –

Private Sub cmdVariableCount_Click()

End Sub

Don’t forget, this isn’t anything special. It just defines the code boundaries for that particular item. It knows where the Click event of cmdVariableCount starts (the Private Sub bit) and knows where it finishes (the End Sub bit). You then code all the complicated stuff between those lines.

  • Type in the following:
CountClick = CountClick + 1Msgbox "You've clicked me " & CountClick & " times!"

I’ll explain what this code does. First, it sets CountClick to equal whatever it is at that moment, plus one. So when we first start the program, it equals zero. Then when we run this code, it adds one to it. The next time we run the code, another one is added, and so on.

The second line of code displays a simple message box saying "You’ve clicked me " and then uses the ampersand character to stick in the value of our CountClick variable. We then use the & character once more to add " times!" to the message.

Top Tip: The ampersand (&) character just sticks bits of the message together. If you’re interested in how you can fiddle with text in VB, be sure to read this article on string manipulation.

If everything goes a Ned Flander’s hokily-dokily, we should get a small program that will display the number of times you clicked the button.

  • Press F5 to run your program and click on the button a few times.

Does it work? Wahay!

Just to recap, we simply declared a variable in the General Declarations section using the format:

Dim VariableName as DataType

We then referenced and changed the variable in code. Now is that supercool or what?

Password protect your PC with help from the VB Voice!

First off, let’s get a few facts straight. When it comes down to computer security, the world is under some kind of delusion. Every hacker film I watch seems to contain a spotty teenager attempting to break into the world’s most powerful computer.

Err, by the way, that same computer also hosts the world’s mostuser-friendly interface. Gee, that’s lucky – if the audience saw a real-lifegreen ol’ mainframe screen, viewer numbers would rapidly decrease.

And why does he ALWAYS manage to guess the password on his third and final sweat-breaking try? Sheesh!

In this short section, we’ll be creating our own mini-security program utilising a combination of techniques we’ve already learned and a couple we’ve yet to explore.

Open Visual Basic and create a new Standard Exe. Change the Form1 Name property to “frmLogon” and its caption to “Enter your Password”. Create a text box and change its Name property to “txtPassword”, its PasswordChar property to an asterisk “*” and remove everything from its Text property.

Now add a command button to the form. Change its Name property to “cmdLogon” and its Caption to “Logon”. Your form should look like this:

Now let’s start coding. Firstly, we need to declare a variable to hold the number of times a user has attempted to enter a password.

Don’t forget – to declare a variable, open the code window and move to the (Declarations) section. For instance, you could double click on a blank area of the form and then select (General) from the object drop-down box and (Declarations) from the procedure drop-down box.

Declare as follows:

Dim LoginCount as Integer

Now in the Click procedure of cmdLogon, enter the following code. You don’t need to type in my notes, which begin with the comment symbol – ‘ – these are to help you understand the code.

LoginCount = LoginCount + 1' Increment the variable by oneIf LoginCount > 3 ThenMsgBox "No more tries, you HACKER!"Exit SubEnd If' The above is "conditional logic"' You're saying if the LoginCount variable is greater' than three - in other words, if they've attempted to ' log on more than three times - then tell them where to' go! Exit Sub just stops the code running right' there, ignoring the rest of our procedureIf txtPassword.Text = "TOPSECRET" ThenMsgBox "Password correct! Access granted..."ElseMsgBox "Password incorrect!"End If' The above is another example of conditional logic.' It checks to see if the textbox text is equal to "TOPSECRET". ' If it is, it congratulates them - otherwise it warns them!

Try running the application. It should allow you to attempt an artificial logon. If the password you supply is correct, it will praise you. If not, err, it won’t. If you try checking after three times, the procedure gets angry and ignores your request.

Ahh, the power of programming!

Karl concludes this week’s epic article.

That’s about all for this tutorial, folks. We’ve explained thoseoh-so-important variables and their role in creating an application, plustoyed with a few little-known control properties and enjoyed a greaterunderstanding of the code window.

If you want to play around with Visual Basic before the next tutorial, trylooking up the "Then…Else Statement" topic in your Visual Basic helpfile and playing with some of the given examples.

You might also want to read up on a few neat programming tips from our My Favourite Functions feature.

Don’t forget that I’d love to hear any feedback you have. Please use thebelow form to leave messages for myself…

Until next week, I’m your 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!

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories