The main programming language we will be using in this subject is Visual Basic (in Access XP). Visual Basic (VB) is used because:
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 |
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
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 does 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.
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.
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 "The total of the two numbers is "; total - refers to a string literal "The total of the two numbers is " 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 The total of the two numbers is = 13 would be displayed.
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 waits for the user to input a number. The number input is then saved in the variable named number1.
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:
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
Marks the end of the subroutine called Main.
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.
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.
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.
After creating/opening a database:
Or if a module is already open:
A database can contain many modules. In this subject a module will be considered the same as a program.
After opening a database:
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.
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.
To print module code.
Open a module then:
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.
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 is far pickier 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.
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.
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).
If you don't have MS Access, Excel can be used to develop Visual Basic programs. The Option Compare Database statement used in Access needs to be commented out in Excel.
To run the Visual Basic Development Environment:
Run Excel
Select Tools > Macro > Visual Basic Editor (or Alt+F11)
To create a new Module/Program:
Select Insert > Module
To view existing modules/programs:
Select View > Project Explorer
By default Macros in Excel (including Visual Basic programs) are disabled for security reasons. While is is possible to write Visual basic code in Excel, it is not recommended.
The following problems are taken from the last lecture.
Write a program that allows a user to input their name, then displays Hello student-name.
Run Name ? Jane Hello Jane
' Name: hello ' Purpose: Display a welcome message ' Author: Tim Whitfort
Option Compare Database Option Explicit
Sub Main() End Sub
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
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 |
' 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() End Sub
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.
Written by Tim Whitfort.