The Basics of Visual Basic


This is a beginner’s VB tutorial that is aimed at someone who has no prior experience in programming. This tutorial will cover basic programming principles such as variables, conditionals, loops, etc. It will also describe VB-specific things such as forms, controls, menus, etc.

For your info, there will be no “hello world” example here. I hate and despise that phrase.

Since the material covered in this tutorial is pretty basic, it should work on all versions of Visual Basic. The steps just might be a little different than VB6 (which is what I’m using).


Your first steps


Start up Visual Basic. If everything works fine, you should see a New Project dialog box. Double-click on “Standard EXE” to create a new project. You should now see a window in the middle with the title “Project 1 – Form1 (Form)”. Now click on Run -> Start or press F5 to run the project. Now you can see the same window that was inside the Form window. This acts just like any Windows application and you can move, resize, maximize, and minimize it. Click the X in the corner of the Form1 window to stop the program.


Creating the controls and setting properties


So far, the program doesn’t actually do anything. We’re going to create a simple program where the user enters text into a text box and clicks a command button. A message box will pop up that contains the text in the text box.

To add these controls to the form, use the toolbar on the right. Click the text box button. Now on the form click and drag until it’s a good size then release the mouse button. Add a command button right below it. Right now inside the text box it should say “Text1” and the command button should read “Command1”.

Select the text box to edit its properties. In the Properties window on the right, change the (Name) value to txtMessage. (Getting into the habit of using descriptive names for your controls will come in handy when you’re working on bigger projects in the future). Now scroll down and remove the text in the Text property to make the textbox blank by default.

Rename Command1 to cmdMessageBox. Change the Caption property to “OK”


Adding the code


Now we get to the good part (sort of). Double-click the command button and it will open the code window for that control. Private Sub cmdMessageBox_Click() means it will be called when the button is clicked. I’ll get into the Private Sub part later. Insert this code:

Code:
Dim Message As String
Message = txtMessage.Text
MsgBox Message
Dim Message as String – This declares a variable. A variable is something that can hold a value. You can declare variables of different types. Integer variables can hold numbers. String variables can hold groups of characters. Boolean variables can only hold two values: true and false. So this statement declares a variable called Message that will hold a string value.

Message = txtMessage.text – This puts a value into the variable. In this case, it’s the contents of the text box.

MsgBox Message – MsgBox will pop up a message box (the name says it all). It will contain the data in the Message variable, which contains the data in the text box.


Moving on


So you’ve learned how to create a project, add controls and edit their properties, and insert code. Now it’s time to move on and learn the things you’ll need for almost every non-trivial program you make. I’m not going to explain everything as detailed as I did above. You’ll have to actually think for yourself.. (God forbid!)


Basic math in VB


Math in VB is easy. In the examples below x and y are integer variables.

Addition: x = y + 2
Subtraction: x = y – 2
Multiplication: x = y * 3
Division: x = y / 2 (this will give a decimal if there’s a remainder)
Division: x = y \ 2 (this will round it down if there’s a remainder. Get the remainder with mod)
Mod: x = y Mod 2 (remainder of y / 2)
Exponent: x = y ^ 2


Conditional statements


Conditional statements provide ways for the program to “make decisions” based on certain factors. Conditional statements are used all the time in programming. For instance, if you had a message box asking the user a question, you could store which button they clicked (yes, no) in a variable. Then you could do an action if they clicked yes, or something else if they clicked no. Here’s the code for that:

Code:
Dim Response As Integer
Response = MsgBox("Yes or No?", vbYesNo)
If Response = vbYes Then
    MsgBox "You clicked yes!"
Else
    MsgBox "You clicked no!"
End If
The return value of a message box statement is a number that indicates which button was pressed. There are built-in variables in VB that contain the numbers for certain buttons (vbYes, vbNo, vbCancel).

The above If statement is pretty self explanatory. If the response is vbYes, then pop up the messagebox. Otherwise, pop up a different message box. You can also use ElseIf if you have more than two possibilities:

Code:
Dim Response As Integer
Response = MsgBox("Yes, No, or Cancel?", vbYesNoCancel)
If Response = vbYes Then
    MsgBox "You clicked yes!"
ElseIf Response = vbNo Then
    MsgBox "You clicked no!"
Else
    MsgBox "You clicked cancel!"
End If
There are other operators than “=” that you can use to compare values:

Greater than and less than:
If x > y Then
If x < y Then

Greater than or equal to and less than or equal to:
If x <= y Then
If x >= y Then

Not:
If Not (x = y)

You can also use multiple conditions with And and Or. Using And, both conditions have to be true. Using Or, only one has to be true
If a = b And c = d Then
If a = b Or c = d Then

Pretty easy huh? This VB stuff’s a cinch! But hold on! We also have… Select Case statements!

Code:
Dim Message As String
Message = InputBox("Enter a letter")
Select Case Message
Case "a"
    MsgBox "apples"
Case "d"
    MsgBox "dog"
Case "z"
    MsgBox "zebra"
Case Else
    MsgBox "Try another!"
End Select
This introduces InputBox and Select Case. InputBox pops up a window that prompts the user for text. The return value is the text entered. Select Case takes a variable and checks the value in it. In some cases (no pun intended) it’s a lot easier to use and cleaner than If statements, especially when you need separate code for a lot of different possibilities. For example, if the user entered a number from 1 to 10, and you needed to execute different code depending on which number they entered, you would want to use Select Case.


Loops


Ok, we’re done with conditionals… Now we get into loops. Loops are used to execute the same code multiple times.

For loops

First we’ll do For loops. For loops use a variable to loop a certain number of times. Each time, the variable is incremented. It’s kind of hard to explain without an example:

Code:
Dim I As Integer
For I = 1 To 10
    MsgBox I
Next I
This will execute “Msgbox I” ten times. The first time I will be equal to 1, the second it’ll be equal to 2, etc… Also if you add “Step #” after the basic For statement it will modify the loop so that it goes up by # instead of 1. Here’s a program to calculate square numbers:

Code:
Dim I As Integer, Counter As Integer
Dim FinalText As String
For I = 1 To 99 Step 2
    Counter = Counter + I
    FinalText = FinalText & Counter & ", "
Next I
MsgBox FinalText
There are a couple things here you may not have seen before. You can declare more than one variable with one Dim statement on the same line. You can concatenate (merge) strings using “&”. See NOW we’re starting to write stuff that’s useful already!

Do…Loop loops

These loops are used to execute code WHILE something is true or UNTIL something is true. Example:

Code:
Dim I As Integer
Do
    I = I + 1
Loop Until I = 100
MsgBox I
This code will output “100” in a message box. This code will also output 100:

Code:
Dim I As Integer
Do
    I = I + 1
Loop While I < 100
MsgBox I
So you could use this, for example, to monitor a text box until it holds a certain string:

Code:
Do
    DoEvents
Loop Until Text1.Text = "passwd"
MsgBox "OK"
DoEvents prevents the computer from hanging up in the loop. It allows other processes to do stuff. It loops until the text box has “passwd” then messageboxes “OK”. Pretty simple.

Exit statements

Sometimes during loops there are special conditions where you want to exit the loop early. This can be done with these commands for the different loops:

Exit For
Exit Do


Nesting


It’s also possible to “nest” loops and conditionals. This is useful in some cases. For example, think of a brute force password cracker. It would probably use nested loops (or maybe I’m missing something).

Here’s how to nest suff:

Code:
Dim X As Integer, Y As Integer, Counter As Integer
For X = 1 To 10
    For Y = 1 To 10
        Counter = Counter + X + Y
    Next Y
Next X
MsgBox Counter
Code:
Dim X As Integer, Y As Integer
X = InputBox("Enter a number")
Y = InputBox("Enter another number")
If X = 3 Then
    If Y = 5 Then
        MsgBox "Both numbers are correct"
    Else
        MsgBox "Only the first number was correct"
    End If
ElseIf Y = 5 Then
    MsgBox "Only the second number was correct"
Else
    MsgBox "Neither were correct"
End If

Subs and Functions


Sometimes you’ll be in a situation where you need to execute the exact same code from two different places. Instead of putting the same code in multiple places, you can create a Sub or Function that you can call from anywhere. The only difference between Subs and Functions is that Functions return a value. They can take parameters, which are values passed to them to be used (ex: Msgbox text -> text is a parameter)

Here is a Function to reverse a string:

Code:
Function Reverse(ByVal Txt As String) As String
Dim I As Integer
Dim ReversedTxt As String
For I = Len(Txt) To 1 Step -1
    ReversedTxt = ReversedTxt & Mid(Txt, I, 1)
Next I
Reverse = ReversedTxt
End Function
This introduces some new stuff. ByVal makes sure that the function can’t modify the original variable. Len(x) returns the length of x. Mid gets characters out of the middle of strings. The way it’s used: Mid(string, place, length) where string is the text you want to extract from, place is the position in the string, and length is how many characters to be extracted.

To return a value with a function, you treat the function name like a variable. Reverse = ReversedTxt.

Subs work the same way as functions, except they don’t return anything. Subs are usually used to modify objects on the form. Functions are usually used to modify variables.


Menus


Menus are an important part of Windows applications. They allow access to a lot of features without cluttering the form with command buttons. VB makes it easy to add menus to your forms.

Right click on the form and select Menu Editor. To add a File menu, enter “&File” into the Caption text box. The & character underlines the letter in after it and allows the user to navigate through menus using the Alt key. In Name enter “mnuFile”. Now press enter and it will add File to the list. To add menus within File you can click the right arrow button to indent the entry. Then you add it just like to added the File menu.

To add code to a menu, double-click on the one you want to add code to. A code window will pop up and you can insert code just like you would into any control.


Global variables


Global variables are variables that can be accessed by any Sub. Although they are useful, they should be used only when necessary or else your code will get hard to follow and debug. You declare global variables in the (General) section of the code.

Code:
Option Explicit
Dim X As Integer, Y as Single
Option Explicit forces you to declare variables before you use them. You should put this in the (General) section of every program you make. It will make your life easier.

With the example above, X and Y will be accessible to every Sub in that form. If you want to make variables available to every form, you’ll have to declare them in a module.

To create a module, go to Project -> Add Module then click Open. You can declare variables in the window. Instead of Dim, you should use Global.

Code:
Global X As Integer, Y as Single
This code will make the exact same variables as above, except they will be available to the entire project instead of just one form.


Times and Dates


If you want to use times and dates in your code, it’s pretty easy. The Date function returns the date in the format m/d/yy. The Time function returns the time in the format h:mm:ss AM/PM. So the following code would pop up a message box that says the date and time:

Code:
MsgBox "Today's date is " & Date & " and the time is " & Time
Another useful time function is Timer. It returns the number of seconds passed since midnight. It’s an easy way to tell how long it’s been since something happened. For example:

Code:
Static X As Single
If X = 0 Then
    X = Timer
Else
    MsgBox Timer - X
End If
Put that code in a command button. When you click the button the first time, nothing happens. The second time, it tells you how many seconds passed between the clicks. I’ll explain some of the new stuff:

When you use Static instead of Dim to declare variables, the variable will hold its value even after the Sub ends. This is useful when you don’t need global variables but you want the variable to keep its value.


Closing


By now you should know enough about the language to start making your own simple programs. I’m planning on writing a more advanced tutorial for people who already know something about the language. Be sure to look out for that. For now, if you’re just starting to learn Visual Basic, this will give you a good start. If you don’t know VB, I suggest you at least try it. It’s a great language.

Here are some sites I’ve used along my VB journey:

Planet Source Code
VBCode
MSDN
VB Helper

That’s all for now. Have fun

mjk