Beginners Tutorial

Submitted on: 1/23/2015 12:52:00 AM
By: JoshD (from psc cd)  
Level: Beginner
User Rating: By 18 Users
Compatibility: VB 3.0, VB 4.0 (16-bit), VB 4.0 (32-bit), VB 5.0, VB 6.0, VB Script, ASP (Active Server Pages) , VBA MS Access, VBA MS Excel
Views: 423
     This tutorial is intended as a guide for people new to Visual Basic. It shows common coding conventions and basic use of VB. ============================================== 1. Option Explicit 2. Code Formatting 3. Commenting 4. Variable Types 5. Static Variables 6. Global/Local Variables 7. Public/Private Functions 8. Arrays 9. Constants 10. Control Names 11. Variable/Constant/Procedure Names ================================== NB: The zip file has the HTML file of the tutorial.

This article has accompanying files

Beginners Tutorial

This is my first tutorial to PSC, so please be kind with any comments...

The tutorial is targeted at users who are new to Visual Basic and provides a few simple basic tips that will help you in your coding. These are all useful tips that will speed up your programming and, as your programs get larger, your debugging.

Like many people I am sick of downloading a program to see that the code is along the lines of:

Private Sub Command4_Click()
Dim a, b, c, d
a = Text12.Text
b = Text3.Text
If a = b Then

This tutorial forms a guide on how to write your code to look professional.

Code represents code examples.
Text represents a comment.
Note: Explains some of the code in the examples.
Procedure: a Sub or function.


1. Option Explicit
2. Code Formatting
3. Commenting
4. Variable Types
5. Static Variables
6. Global/Local Variables
7. Public/Private Functions
8. Arrays
9. Constants
10. Control Names
11. Variable/Constant/Procedure Names

Option Explicit (top)

Option Explicit is an extremely useful function of VB, if you refer to a variable that does not exist VB will stop executing the code and inform you of this. If you do not include Option Explicit and misname a variable then VB will assume create a new variable with a value of 0 or null. For example:

Dim myName as String
myName = "BOB"
If myyName = "" Then
   MsgBox "Hello " & myName
End If

If Option Explicit is used VB will stop when the IF statement is reached. If Option Explicit is not used the code will not display a message, as VB will assume myyName is different from myName. It will create the variable myyName (of type Variant) with an initial value of "", because of this the message box will not be displayed.

While this mistake appears obvious, and would be easy to debug, when thousands of lines are used a small mistake can stop the entire code from working.

The Option Explicit keywords should be the topmost line of code for a form or module, before any declarations or procedures.

Code Formatting (top)

The most important aspect when writing code for your programs is the format of the code. This is the first thing another programmer will see when they open your program, and they will be more likely to peruse and attempt to understand your code if it appears friendlier. Formatting is easy to remember:

Inside a procedure code will be should indented one tab.

Public Sub cmdAbout_Click()
   MsgBox "(c) me, 2002"
End Sub

For each IF statement, FOR or DO loop the code should be indented an additional tab.

Public Sub cmdDisplay_Click()
   Dim i as Integer
   For i = 1 to 10
      txtResults.Text = txtResults.Text & i & vbTab & i^2 & vbCrLf
   Next i
   MsgBox "(c) me, 2002"
End Sub

This is far easier to read than

Public Sub cmdDisplay_Click()
Dim i as integer
For i = 1 to 10
txtResults.text = txtResults.text & i & vbTab & i^2 & vbCrLf
Next i
MsgBox "(c) me, 2002"
End Sub

Note: vbTab adds a tab to the text, vbCrLf adds a Carriage Return and Line Feed characters, which together make the text go to a new line. These are both VB constants, explained below. i^2 is simply a mathematical function, representing i x i, ^ represents the mathematical function power. Therefore i^3 means i x i x i.

VB does not insert a Tab character, instead it will insert spaces that act in a similar way. The number of spaces per tab can be set in the program options.

Commenting (top)

A comment is a piece of text in your program that is not intended to be executed as a command. A comment is indicated by a single quotation mark before the text. The comment can appear on the same line as code but anything after the quotation will be considered a comment

Commenting is very useful to remind yourself what code does and is very important in indicating to other programmers unfamiliar with your code what each piece of code does.

If submitting a program to PSC, a good idea is to add your name, e-mail, the project name and the date at the top of the first from/module this makes it easier for other users to contact you if they wish to use your code. You also may wish to add a short description of your program. e.g.

'Program: Date Finder
'Author: I. Rule <>
'Date: 1/1/2002
'This program will accept a date and check
'whether it is a leap year.

Comments should be used within the code to explain its function.

Dim leap as Boolean
leap = (year Mod 4 = 0)
  'Is this a leap year?

If a line of code is long it may be easier to write the comment before the line of code, to save yourself continually scrolling to see the comments.

Dim leap as Boolean
'Is this a leap year?
leap = (year Mod 4 = 0)

It is recommended that you do not over comment this can make code appear cluttered and if unnecessary, will slow you down. For example:

Dim leap as Boolean, year as Integer
year = Val(cmdYear.Text) 'Get the year from the text box
leap = (year Mod 4 = 0)  'Is this a leap year?
MsgBox leap              'Display a message box indicating whether this is a leap year.

Note: Val(text) will give you the numerical value text, this is useful incase the user types a letter instead of a number, which would cause the program to crash, instead Val(text) will return 0. The Mod operator gives the remainder, so 5 Mod 2 would give 1(the remainder of 5 divided by 2). The formatting of leap = (year Mod 4 = 0) is an easy way to get a True/False value. year Mod 4 gives a number, if this number is 0 then (year Mod 4 = 0) gives True, if not it gives False. Therefore leap receives its correct value. The brackets are not necessary but make the code easier to understand.

Use your own judgment whether code needs to be commented, keeping in mind whether it is for your own or others benefit.

Variable Types (top)

Visual Basic has the following variable types:

Type Description Example
Date Stores a date/time combination 1:46:32 AM 17-02-2002
String Stores a "string" of text without formatting Hello Bob
Integer A non decimal number -32768 to +32768 199
Byte An integer from 0 to 255, inclusive 16
Long An integer extending to billions 1132434
Double Stores decimal and large numbers 1.0002
Single Stores large numbers  
Boolean A single bit, stores True or False True
Variant A variant should not be used, it can store values of any of the above types, but is very memory intensive and is bad programming practice to use them.  

String, Integer and Boolean are the most common, but as your programs become more advanced you will need to use Long, Double and Date

A variable is declared as such:

Dim var as Boolean

If you wish to use this variable in other modules/forms declare it as public:

Public var as Boolean

A variable that is not given a type becomes a variant by default. Do not do this.

Dim var

To save space/time variables can be defined in a single line.

Dim var as Boolean, personName as String, age as Integer, siblings as Integer

Do not declare them in the following fashion

Dim var1, var2, var3 as Boolean

var1 and var2 will become Variant type. Only var3 will be a Boolean type.

Static Variables (top)

If the keyword Static is used in place of Dim the variable will retain its value. For example:

Private Sub cmdCount_Click()
   Static count as integer
   count = count + 1
   MsgBox count
End Sub

The first time the button is pressed (the procedure is run) a message box will display "1" the second time it would display "2" and so on. If Dim were used:

Private Sub cmdCount_Click()
   Dim count as integer
   count = count + 1
   MsgBox count
End Sub

The count would be re-created each time, and it would revert to 0, therefore pressing the button would only ever display 1. Static variables are rarely required and in most cases a global variable is easier to use and more suitable.

Static variables cannot be global, i.e. they should only exist within procedures.

Global/Local Variables (top)

A variable can be either declared locally or globally. A local variable is defined within a procedure and can only be accessed from within that procedure. A global variable is defined outside a procedure at the top of the page of code for that form or module. It can be accessed by all procedures in that module/form, and will obviously not lose its value once a procedure has finished executing. e.g.


Dim myName as Stirng             'Global variable - can be used by any procedure of frmMain
Dim myAge as Integer             'Global variable - can be used by any procedure of frmMain
Public peopleCount as Integer    'Public global variable - notice it can be used by modChecks

Private Sub cmdRecord_Click()
   Dim valid as Boolean          'A local variable - it can only be used in this sub
   valid = chkValid.Value
   If valid = true Then
      myName = txtName.Text
      myAge = txtAge.text
      peopleCount = Val(txtCount.text)
      message = txtMessage.text
   End If
End Sub

Private Sub cmdDisplay_Click()
   MsgBox "Name " & myName
   MsgBox "Age " & myAge
End Sub



Public message as string       'Public global variable - notice it can be used by frmMain

Public Sub CheckMaximum()
   If frmMain.peoplCount > 5 Then
      MsgBox message
   End If
End Sub

Notice frmMain.peopleCount is used in CheckMaximum when referring to the variable. This applies when a form or module gets the value of a variable belonging to another form. If the variable belongs to a module then the form or module can directly refer to it directly, as is the case for the variable message. These variables are used as an example - it is up to you to decide whether the variable is declared in the module or form.

Public/Private Functions (top)

Similar rules to these apply to procedures. Private procedures can only be used within their own form or module. Public ones can be used by any form or module, but if they belong to a form the forms name must be written before the procedure name.

GENERAL RULE: If a variable, procedure is used in more than one form it should be placed in the module, if not it is best placed in the form it is used in.

Arrays (top)

An array or variables is useful when you need to store values that belong in a list. The can be declared as follows:

Dim name(1 to 100) as String

An array can also be declared like so:

Dim name(100) as String

This would equate to:

Dim name(0 to 100) as String

In most cases when using arrays the list begins at 0, not 1.

The same rules regarding the Public keyword apply, except for two changes:
1. All arrays must be global (i.e. not declared within a procedure).
2. An array that is declared in a form cannot be Public.

It is possible to define an array without specifying a length:

Dim userName() as String

In this case the length must be specified lasted using ReDim. This will allow you decide on a length after some code has been executed. A ReDim statement can be called more than once for any array, however each time the values for each position in the array will be lost.

Dim userName() as String

Private Sub cmdSetLength_Click()
   Dim people as integer
   people = Val(txtPeopleCount.Text)
   ReDim userName(1 To people)
End Sub

An array like those above represent a single dimension. It is possible to have as many dimensions as you like (although three is probably the maximum you will need). Note that if you create an array with many dimensions you may fun out of memory, as a 8 dimensional array like so userName(1 To 10, 1 To 10, 1 to 10 ...) as String is equivalent to 100,000,000 variables.

Multi-dimensional arrays are declared in the following fashion:

Dim userName(1 To 10, 1 To 10) as String


Dim userName() as String

Public Sub SetDimensions()
   ReDim userName(1 To 10, 1 To 10)
End Sub

Constants (top)

Constants provide an easy way to remember reoccurring numbers or text without creating a variable. Constants cannot be changed at run-time. Typical use may be:

Const PI = 3.141592653589

A constant can only be global. A public constant can only be declared in a module using the syntax:

Public Const PI = 3.141592653589

Visual Basic constants

Visual Basic has its own inbuilt constants. Each only begins with the prefix vb. Previously vbTab and vbCrLf were discussed. The most commonly used are for the basic colours and for key ASCII values (used in the KeyDown and KeyPress procedures). For a full list check your help file.

Example Value
vbKeyEscape 27
vbKeyRight 39
vbBlue 16711680

Control Names (top)

Naming controls is an important part of programming. It should be done as each control is placed on the form not after the entire layout is designed. The prefix for each control should be standard and suggest what type of control it is. The generally accepted prefixes for the most common controls are:

Control Prefix
Command Button cmd

If a label is not used for input or output it is acceptable to leave its default name.

Text Box txt
Form frm
Picture Box pic
Image img
Timer tmr
Menu mnu
Check Box chk
Option Button opt

By doing this your code will be far easier to interpret, a control named txtAge is far more descriptive that one named age, which could be a button, textbox or even a label. It also means that you don't run into trouble when you want (for example) a button and textbox to have the same name. Controls can also exist in arrays - if you copy and paste a control it will ask you if you would like to create an array. This functionality is rarely needed, but if it is the Index property represents its position in the array. Controls can only exist is one-dimensional arrays.

Variable/Constant/Procedure Names (top)

The naming convention of variables/constants/procedures is not vital, but is good programming practice and is extremely helpful to someone examining your code. There is one rule for each type:

Type Rule Example
Variables The name has correct cases except for the first letter, which is always lower case. myName
Constants The entire name is uppercase. DAYSPERYEAR or DAYS_PER_YEAR
Procedures All letters are correct cases. CalculateAverage

If you have declared a variable then VB will automatically convert all instances of it in your code to the case you used when you declared it. This can be used if you are unsure what the name of the variable was, if you type is deliberately in the wrong case and it is correct the case will be changed to mach that of the declaration.

For example if you are unsure if the variable boxColour was spelt boxColour or boxColor then type: BOXCOLOR and press space/enter, because there is no variable by this name the case will remain unchanged. Therefore if you retype the text as to BOXCOLOUR the case will automatically change to boxColour.

winzip iconDownload article

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzip to decompress it.Virus note:All files are scanned once-a-day by Planet Source Code for viruses, but new viruses come out every day, so no prevention program can catch 100% of them. For your own safety, please:
  1. Re-scan downloaded files using your personal virus checker before using it.
  2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.
  3. Scan the source code with Minnow's Project Scanner

If you don't have a virus scanner, you can get one at many places on the net

Other 12 submission(s) by this author


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

Other User Comments

 There are no comments on this submission.

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)

To post feedback, first please login.