Lecture 6 - Introduction to Visual Basic


Home > Lectures > Lecture06

Objectives

Contents


1. Visual Basic

The main programming language we will be using in this subject is Visual Basic (in Access XP). Visual Basic (VB) is used because:

2. A Simple Visual Basic Program

Pseudo Code

addTwoNumbers()
    Input number1, number2
    total = number1 + number2
    Display total
STOP

Data Dictionary

Name Data Type Description
number1 Integer The first number to be added
number2 Integer The second number to be added
total Integer The total of number1 and number2 added together

Visual Basic Code

Note: Line numbers have been added to the following code to make it easier to refer to the code.

 1  ' Name: addTwoNumbers
 2  ' Purpose: To add 2 number together and display the result
 3  ' Author: Tim Whitfort
 4
 5  Option Compare Database
 6  Option Explicit
 7
 8  Sub Main()
 9
10      ' Variable declarations
11      Dim number1 As Long
12      Dim number2 As Long
13      Dim total As Long
14
15      ' Input the numbers
16      number1 = InputBox("First number ? ")
17      number2 = InputBox("Second number ? ")
18
19      ' Add the numbers together
20      total = number1 + number2
21
22      ' Display the total
23      Debug.Print "The total of the two numbers is "; total
24
25  End Sub

3. Introduction to the Visual Basic Language

Comments (lines 1-3, 10, 15, 19, 22)

Comments are provided to help someone reading the program to understand it. Comments start with an apostrophe('). Everything from the ' on is ignored by the compiler and do not change how the program runs. The comment on line 2 briefly explains what the program does. The comment on line 15 helps the reader understand the purpose of the code on the following two lines.

Option (lines 5-6)

Put these in each program. The meaning will be discussed later.

Sub Main() (line 8)

The start of the main part of the program. This contains declarations (of data to be stored) and executable code (actions to be performed). Sub is short for Subroutine. Sub always has a matching End Sub to mark the end of the subroutine. The name of this Subroutine is Main.

Declarations (lines 11-13)

A programmer can create their own names for things in a program. The names are called identifiers.

The program needs to store 3 values while it is running, these are declared in lines 11-13. Before variables can be used in a program they must be declared. Variables are declared in a Dim statement.

Identifiers (e.g. variables names) start with a letter and can be followed by letters, digits or underscores. However a common convention is to use lowercase, except for the first letter of each word, from the second word onwards. e.g. count, studentName, thisIsALongIdentifierName.

The computer represents numbers in different ways, this is to save space and maintain precision where possible. Numbers that are always whole numbers (no fraction part) are called integers. Integers are declared as Long in Basic. Numbers that may have a fraction part are called floating point (or real) numbers and are declared as Double in Basic.

Variables that aren't numbers, for example: customer names and addresses are called Strings. Strings can contain any character. Strings can't be used in calculations.

Generic Name Data Type in VB Example Declaration Example Values Description
integer Long Dim count As Long 0, 123, -99, 10000000, -1234567 Long is short for Long Integer
floating point Double Dim x As Double 0.4, -0.00123, 7659.23 Double is short for for Double precision floating point number
string String Dim name As String "", "Fred", "123X", "Once upon a time", "g*&k $88n"  

Literal values are numbers or strings that are taken exactly as they are: For example: 0, 123, 0.4 are numeric literals, and "", "123X" and "Once upon a time" are string literals. String literals are enclosed in double quotation marks e.g. "Fred". Numeric literals are not enclosed in quotes e.g. 123.

Variables hold a single value at a time, they are referred to by a variable name (an identifier). Variables are stored in memory. To be able to retrieve the value the programmer needs to specify which variable they are referring - here the name is used. Variables are named storage locations.

Line 23: Debug.Print "Total = "; total refers to a string literal "Total = " which is printed out exactly as stated and a variable named total, where the value held in total is displayed, not the name. So if total has the value 13, then the message Total = 13 would be displayed.

InputBox (lines 16-17)

InputBox is used to input a number or a string. The message inside the brackets is displayed  (First number ?), the user types a value and the answer is stored in the variable on the left hand side of the equals

number1 = InputBox("First number ? ")

The above line displays the message "First number ?" on the screen and wait for the user to input a number. The number input is then saved in the variable named number1.

Calculations (line 20)

Calculations use the arithmetic operators: (), * (multiply), / (divide), + (add), and - (subtract). The calculation of the right hand side of the equals sign is evaluated and the answer is stored in the variable on the left hand side of the equals sign.

Arithmetic operators are evaluated in a defined order: firstly (), then working from left to right * or /, then working from left to right + or -.

Examples:

 


Debug.Print (line 23)

Displays literal and/or the values held in variables on the screen in the Immediate Window.

Debug.Print "The total of the two numbers is "; total

Displays the string literal "The total of the two numbers is " and the value held in the variable named total. e.g. The total of the two numbers is 13

End Sub (line 25)

Marks the end of the subroutine called Main.

4. The Visual Basic Development Environment

We will be using Visual Basic within MS Access XP (2002). MS Access is available in MS Office Professional or as a standalone product. Earlier or later versions of Access might be suitable.

Creating a New Database

  1. Start Access
  2. File->New...
  3. From the New File window on the right hand side of the Access window, Select Blank Database
  4. Indicate where you want to store the database on your H: drive
  5. Type in an appropriate name and click the Create button

This creates an Access .mdb (Microsoft Data Base) file. We will be using this to store our programs. For example, you might use a single database file to store all of your tutorial exercises.

Open an Existing Database

After starting Access, a list of database files appears on the right hand side of the window. Select the desired database file, OR select File->Open from the menus etc.

Creating a New Module

After creating/opening a database:

  1. Under Objects click on Modules on the left hand side of the window
  2. Click the New button at the top of the window to create a new module
  3. In the Properties window click on the text box next to (Name). The name will probably me something like Module1 or Module2 etc. Change the module name to the desired name for the program. (If the Properties window is not displayed, use View->Properties Window or F4 to display it)

Or if a module is already open:

  1. Select Insert->Module or click the Insert Module toolbar button.
  2. In the Properties window click on the text box next to (Name). The name will probably me something like Module1 or Module2 etc. Change the module name to the desired name for the program. (If the Properties window is not displayed, use View->Properties Window or F4 to display it)

A database can contain many modules. In this subject a module will be considered the same as a program.

Opening an Existing Module

After opening a database:

  1. Under Objects click on Modules on the left hand side of the window
  2. Select the desired module from the list

or Select a module from the Project Explorer window by double clicking on it. If the Project Explorer is not displayed, select View->Project Explorer.

Save Database

Click on the Save button or select File->Save to save the database and the modules in it. You will be prompted whether you want to save changes to each module that has been modified.

Print

To print module code.

Open a module then:

  1. File->Print...
  2. Click the Setup... button
  3. Ensure that the right Printer Name and Paper Size (A4) are selected before printing and click the Ok button
  4. Click the Ok button to print

Editor

The editor is used to type and modify a module (program). It works much like a simple word processor. The editor uses Syntax Highlighting - this  uses different colours to make the code easier to read e.g. (by default) comments are in green, keywords (e.g. Sub, End, If) are in blue and most other things are in black.

Most of the navigation keys that work in a word processor also work in the editor.

Compiling

Before the program can be run it must be free of Syntax Errors. A Syntax Error is the incorrect use of the language - the code does not conform to the rules of the language. This is equivalent to using incorrect grammar in English - except that a compiler if far picker about language than a grammar checker. The Compiler is a program that checks for syntax errors. Syntax errors are also known as Compiler Errors.

Syntax errors can be detected by the compiler and highlighted when: (a) typing in a line of code and moving the cursor to another line, or (b) when compiling the whole program.

To compile the program code select Debug->Compile database-name. This will compile the whole database but does not run the program. If the program has not been changed since it was last successfully compiled this menu item will be disabled. Alternatively just run the program and any syntax errors will be shown, if the program has no syntax errors it will then be run.

Running

To compile and then run the program, position the cursor between Sub Main and End Sub then click the Run button (a blue triangle like a play button on a tape/CD player) or press F5 or select Run->Run Sub/UserForm.

Immediate Window

Anything that is displayed by the program using Debug.Print is shown in the Immediate Window
If you can't see the Immediate window select View->Immediate Window or press Ctrl+G.

The immediate window can be cleared by placing the cursor in the immediate window and Selecting All (Ctrl+A or Edit->Select All) followed by Delete or Cut (Ctrl+X or Edit->Cut).

5. Example Programs

The following problems are taken from the last lecture.

Problem 1: Hello user-name

Write a program that allows a user to input their name, then displays Hello student-name.

Example Run

Run
Name ? Jane
Hello Jane

Write the Program (Coding in Visual Basic)

' Name: hello
' Purpose: Display a welcome message
' Author: Tim Whitfort
Option Compare Database
Option Explicit
Sub Main()

    ' Declare variables


    ' Input the users name


    ' Display the a welcome message


End Sub

Problem 2: Supermarket Item Value

It can be difficult to compare the price of items in a supermarket when the items are different sizes. In some countries, supermarkets display a price per 100 grams for items to make comparisons easier. For example, which is the better value, 250g of honey at a cost of $5.00, or 500g for $8.00, or 375g for $5.95? Write a program to allow the user to input the weight in grams and the cost of an item, and display the cost per 100g. Hint: the weight needs to be converted to lots of 100g (e.g. divide the weight in grams by 100).

Example Run

Run
Weight (g) ? 250
Cost ($) ? 5.00
Cost per 100g = $2.00

Pseudo Code

calcBestItemValue()
    Input weight, cost
    weightInLotsOf100Grams = weight / 100
    costPer100Grams = cost / weightInLotsOf100Grams
    Display costPer100Grams
STOP

Data Dictionary

Name Data Type Description
cost Double The cost of the item in $.
costPer100Grams Double The cost in $ of 100 grams of the item.
weight Integer The weight of the item in whole grams.
weightInLotsOf100Grams Double The weight of the item in 100 grams lots. e.g. an item weighing 325grams is 3.25 x 100g

Write the Program (Coding in Visual Basic)

' Name: calcBestItemValue
' Purpose: Determine the best value items at a supermarket by weight and price
' Author: Tim Whitfort
Option Compare Database
Option Explicit
Sub Main()

    ' Declare variables





    ' Input weight and cost



    ' Calculate the weight in multiples of 100 grams


    ' Calculate the cost per 100 grams of the item


    ' Display the cost per 100 grams of the item


    ' Display the cost per 100 grams formatted to 2 decimal places


End Sub

What's Next?

In the next few lecturers we will look at selection. So far statements have been executed from top to bottom exactly once in a program run. Selection allows statements to be optionally executed depending on some condition, allowing different actions to be performed depending on the circumstances.

Key Points

Further Reading


Previous Lecture | Lecture Index | Next Lecture | Tutorial
Last modified 05-Jan-2005 by Tim Whitfort.
Copyright © 2003-2005
Tim Whitfort