Basic Language Guide


Home

Contents


Introduction

This is a brief overview of MS-Access Visual Basic language. It is intended as an introduction, covering the most commonly used statements, subroutine and functions of relevance to beginning programmers. It does not cover GUI (Graphical User Interface) or OOP (Object Oriented Programming) or any intermediate or advanced level topics.

Visual Basic is often referred to as VB (VeeBee).

Ctrl+Break to stop execution

Comments

Format

' comment-to-end-of-line

Examples

' Purpose: Calculate the GST on an item.
Dim studName As String  ' The name of a student e.g. Anne Smith

Line Continuation

If a line of code is to continue over 2 or more lines each line (except for the last) must end with the line-continuation-character underscore "_". The line-continuation-character must be preceded by one or more blanks (space or tab).

Format

statement-part-1  _
statement-part-2  _
. . .             _
statement-part-n

Examples

Debug.Print "The name of the student is "; studName; ".  _
            "Their student number is "; studNum;  _
            " and there course is "; courseName

priceIncludingGST = itemPrice +   _
                    (itemPrice * gstRate)   _
                    / 100)
 

Keywords

Keywords (also known as reserved words) are reserved by Visual Basic for special purposes, and cannot be used for any other purpose. Examples of keywords are: If, Else, While, Dim, and Function. For example, you cannot give a variable the name While.

Naming Identifiers

Identifiers are names given to things by a programmer. This includes the names of constants, variables, subroutines, functions, parameters etc.
The language is not case sensitive e.g. the variable names count, Count, COUNT and counT all refer to the same variable. VB automatically changes the capitalization of identifiers to match their declaration.

Naming rules:

Declarations

Constant Declarations

Constants do not change in value.

Format

Const constant-name [As data-type] = constant-expression

Note : [] denotes optional

Examples

Const MINUTES_IN_HOUR As Long = 60
Const MINUTES_IN_DAY As Long = MINUTES_IN_HOUR * 24
Const MILLIMETRES_PER_INCH As Double = 25.4
Const GST_RATE As Double = 10 / 100

Const COMPANY_NAME As String = "Acme Computers"
Const DEBUG_RUN As Boolean = True
 

Variable Declarations

Variables may change in value when the program runs. For example, the value of a variable may change if a new value is input by the user.

Format

Dim variable-name As data-type,
variable-name As data-type, ...

Examples

Dim averageAge As Double
Dim length As Double
Dim mark as Long
Dim populationSize As Long
Dim result As String
Dim studentName As String
Dim totalAge As Integer
Dim validLength As Boolean
Dim x As Double

Standard Data Types

Data Type
Category
Size (Bytes)
Description
Integer
Integer number
2
Range: -32,768 to 32,767
Long
Integer number
4
Range: -2,147,483,648 to 2,147,483,647
Double
Floating point number
8
Accuracy: 15 or 16 significant digits. Range: +/- 1E-308 to 1E308 (approx)
Boolean
Logical
2
True or False
String
String
10 + length of string
Size: up to approx. 2 billion bytes (variable length string) Not sure when it uses fixed length strings (up to 65,400 bytes long)

Operators

Operators are used to perform operations on one or more values called operands. An example of an operator is "+", the arithmetic operator for addition. In the following expression, 3 and 2 are operands and + is an operator:  x = 3 + 2.

Arithmetic Operators

Arithmetic operators are used to perform calculations.

Assume x is 2 in the following examples.

Operator
Description
Example
Example Result
()
Brackets
 
 
^
Raise to the Power
y = x ^ 3
(x cubed) is 8
-
Negation
y = -x
(-2) is -2
*
Multiplication
y = x * 3
(2 * 3) is 6
/
Division
y = 7 / x
(7 / 2) is 3.5
\
Integer division
y = 7 \ x
(7 \ 2) is 3 e.g. 2 into 7 goes 3 times (and 1 remainder).
 If the operands are non-integers then their rounded values are used in the calculation e.g. y = 7.4 \ 2.9 is the same as y = 7 \ 3 which is 2.
Mod
Modulus (remainder of integer division)
y = 7 Mod x  
(7 Mod 2) is 1 e.g. 2 into 7 goes 3 and 1 remainder. If the operands are non-integers then their rounded values are used in the calculation e.g. y = 7.4 Mod 2.9 is the same as y = 7 Mod 3 which is 1.
+
Addition
y = x + 3
(2 + 3)  is 5
-
Subtraction
y = x - 3
(2 - 3) is -1

Comparison Operators

Comparison operators are used to compare two values. Assume x is 2 and y is 3 in the following examples.

Operator
Description
Example
Example Result
=
Equal
x = y
(2 = 3) is False
<>
Not Equal
x <> y
(2 <> 3) is True
<
Less Than
x < y
(2 < 3) is True
<=
Less Than or Equal To
x <= y
(2 <= 3) is True
>
Greater Than
x > y
(2 > 3) is False
>=
Greater Than or Equal To
x >= y
(2 >= 3) is False

Logical Operators

Logical operators are used to combine or modify sub-conditions. Assume x is 2 and y is 3 in the following examples.

Operator
Description
Example
Example Result
Not
The result is the opposite of the operand
Not (x <= y)
Not (2 <= 3) is (Not True) is False
And
The result is True if both operands are True otherwise the result is False.
x > 7 And y = 12
(2 > 7 And 3 = 12) is (False And False) is False
Or
The result is False if both operands are False otherwise the result is True.
x <> y Or y >= 10
(2 <> 3 Or 3 >= 10) is (True Or False) is True

String Operators

Assume lastName is "Smith" and firstName is "Rachel" in the following examples.


Example
Example Result
&
String concatenation (combining strings together)
fullName = lastName & "," & firstName
("Smith" & ", " & "Rachel") is "Smith, Rachel"

Operator Precedence

Operator precedence refers to the order that operators are evaluated in an expression. Operators of equal precedence are evaluated from left to right. Brackets (Parenthesis) can be used to change the order of precedence of expressions.
 
Precedence Operator Type Operators
1   ()
  Arithmetic Operators  
2   ^
3   - (negative sign)
4   *, /
5   \
6   Mod
7   +, -
  String Operator  
8   &
  Comparison Operators  
9   =, <>, < <=, >, >=
  Logical Operators  
10   Not
11   And
12   Or

Sequence

Assignment

Format

variable = expression

Examples

totalAge = 0
length = 12.3
x = length * 4
studentName = "Joan Smith"
result = ""
validLength = True

Input (InputBox)

InputBox is used to display a message to prompt a user for a value, and store the value typed by the user in a variable.

Format 

variable = InputBox(prompt-message)

Examples

studentName = InputBox("Please input the students name")
length = InputBox("Length of item in mm ?")
mark = InputBox("Mark ? ")

Display (Debug.Print)

Debug.Print is used to display values on the screen. The values may be literals such as "Final mark:" or the values held in variables. If the values to be printed are separated by semicolons (;) they are displayed next to each other, if a comma (,) is used the value following the semicolon  is displayed at the next tab stop (approximately every 14 characters: positions 1, 15, 29, 43 etc)..

Format

Debug.Print value; value; ...
Debug.Print value, value, ...

Examples

Debug.Print
Debug.Print "Hello World"
Debug.Print averageAge; totalAge
Debug.Print "Student : "; studentName, "Final Mark: "; mark; "%"

Selection

If-Else

An If statement allows statements to only be performed under certain conditions.

Format

If condition Then
    statement
    statement
    ...
End If
 

If condition Then
    statement
    statement
    ...
Else
    statement
    statement
    ...
End If  

If condition Then
    statements
Else
    If condition Then
        statements
    Else
        If condition Then
            statements
        Else
           statements
        End If
    End If
End If
 
Note: the Else part is optional. Use it where required by the logic.

Examples

If lineNumber >= 50 Then
    Debug.Print ""
    Debug.Print "Student Number", "Student Name"
    lineNumber = 0
End If  

If length >= 0 And length <= 4500 Then
    Debug.Print "Small/Medium sized car"
Else
    Debug.Print "Large Car"
    Debug.Print "Excess is $10"
End If  

If mark >= 80 Then
    grade = "A"
    comment = "Excellent"
Else
    If mark >= 70 Then
        grade = "B"
    Else
        If mark >= 60 Then
            grade = "C"
        Else
            If mark >= 50 Then
                grade = "D"
            Else
                grade = "N"
                comment = "Poor"
            End If
        End If
    End If
End If

Iteration (Repetition)

For

A For loop repeats the statements in the loop a predetermined number of times.

Format

For counter = start-value to end-value [Step step-amount]
    statement
    statement
    ...
Next [counter]

Examples

For i = 1 To 10
    Debug.Print i
Next

For count = 10 To 0 Step -1
    Debug.Print count
Next count

For x = 10 To 12.8 Step 0.1
    y = x * x
    Debug.print "x: "; x, "y: "; y
Next

While

A While loop repeats the statements in the loop, while the condition is true.

Format

While condition
    statement
    statement
    ...
Wend

Examples

count = 1
While count <= 10
    Debug.Print count
    count = count + 1
Wend

mark = InputBox("Mark (0 to 100) ?")
While mark < 0 Or mark > 100
    Debug.Print "Invalid mark, must be between 0 and 100"
    mark = InputBox("Please re-enter mark (0 to 100) ?")

Wend

Programs

Format

Option Compare Database
Option Explicit

Sub Main()
    declarations

    statement
    statement
    ...
End Sub
 

Example

Option Compare Database
Option Explicit

Sub Main()
    ' Declare variables
    Dim number1 As Double
    Dim number2 As Double
    Dim sum As Double

    ' Executable code: Actions
    number1 = InputBox("Number 1 ?")
    number1 = InputBox("Number 2 ?")
    sum = number1 + number2
    Debug.Print sum
End Sub 

Programmer Defined Subroutines and Functions

Format - calls

Call subroutine-name()
Call
subroutine-name(parameter, parameter, ...)

subroutine-name
subroutine-name parameter, parameter, ...

function-name()
function-name(parameter, parameter, ...)

Examples - subroutine or function method calls in a program

Option Compare Database
Option Explicit

Sub Main()
    Call displayTenStars()
    Call displayAverage(count, total) 

    month = inputMonth()
    If oddNumber(month) Then
        ...
    End If
    volume = 4 /3 * PI * cube(radius)
    max = maximumNumber(a, b)
End Sub

Subroutines

Format - calls

subroutine-name
subroutine-name parameter, parameter, ...

or

Call subroutine-name()
Call
subroutine-name(parameter, parameter, ...)

Examples - calls

Sub Main()
    displayTenStars

    Call displayTenStars()
    displayAverage count, total 
    Call displayAverage(count, total) 
End Sub

Format - declarations

Sub subroutime-name()
    statement
    statement
    ...
End Sub

Sub subroutime-name(parameter As data-type, parameter As data-type, ...)
    statement
    statement
    ...
End Sub

Examples - declarations

Sub displayTenStars()
    Dim numStars As Integer
    For numStars = 1 to 10

        Debug.Print "*"
    Next
    Debug.Print ""
End Sub

Sub displayAverage(count As Integer, total As Integer )
    If count > 0 Then
        average = total / count
        Debug.Print average
    Else
        Debug.Print "Error, nothing to average"
    EndIf
End Sub

Functions

Format - calls

function-name()
function-name(parameter, parameter, ...)

Example - calls

Sub Main()
    month = inputMonth()
    If oddNumber(x) Then
        Debug.Print x; " is an odd number"
    End If
    volume = 4 /3 * PI * cube(radius)
    max = maximumNumber(a, b)
End Sub

Format - declarations

Function function-name() As return-data-type
    statement
    statement
    ...
    function-name = result
End Function

Function function-name(parameter As data-type, parameter As data-type, ... ) As return-data-type
    statement
    statement
    ...
    function-name = result
End Function

Examples - declarations

Function inputMonth() As Integer
    Dim monthNumber As Integer
    monthNumber = InputBox("Month number (1 to 12) ?")
    While monthNumber < 1 Or monthNumber > 12
        Debug.Print "Error invalid month number"
        monthNumber = InputBox("Month number (1 to 12) ?")
    Wend
    inputMonth = monthNumber

End Function

Function oddNumber(number As Integer) As Boolean
    If number Mod 2 = 1 Then
        oddNumber = True
    Else
        oddNumber = False
    End If
End Function

Function cube(number As Double) As Double
    cube = number * number * number
End Function

Function maximumNumber(number1 As Integer, number2 As Integer ) As Integer
    If number1 >= number2 Then
        maximumNumber = number1
    Else
        maximumNumber = number1
    End If
End Function

Standard Functions

Maths Functions

Function
Argument Type
Result Type
Description
Sqr
Any numeric expression
Double
Square root of a number. y = Sqr(x) is Sqr(9) is 3.0
Int
Any numeric expression
integer or floating point
Rounds the number down to the biggest whole number that is less than or equal to the number. e.g. Int(9.3) is 9, Int(9.7) is 9, Int(-9.3) is -10, Int(-9.7) is -10

String Functions

Function
Argument Type(s)
Result Type
Description
Format numeric expression, format-string String Format: returns a formatted string. e.g. str = Format(price, "#,##0.00")
Space integer String Returns a string containing the number of spaces specified. e.g. Debug.Print name; Space(20); address

Str

numeric expression String A leading space is allowed for the sign, so a leading blank appears for positive numbers. e.g. numStr = Str(123) ' numStr is " 123".
Also see the CStr and Format functions.

Data Type Conversion Functions

Functions to convert to a type start with a C and are followed by an abbreviated form of the data-type name.
e.g. CInt converts a value to an Integer, CDbl converts a value to a Double.

The functions are: CDbl,  CInt, CLng, CStr,

Function
Argument Type(s)
Result Type
Description
CDbl any compatible type Double Returns a Double corresponding to the argument. e.g. x = CDbl("123.45")
CInt any compatible type Integer Rounds a floating point number to the nearest whole number e.g. CInt(9.3) is 9, CInt(9.7) is 10, CInt(-9.3) is -9, CInt(-9.7) is -10. If the value is not a valid number for the data-type then a type mismatch error is thrown (#13). eg CInt(1a2).
CLng any compatible type Long Same as CInt, except for bigger numbers. e.g. i = CLng("123456789")
CStr any compatible type String Returns a string equivalent of the argument. e.g. numStr = CStr(123)

Local Variables and Global Variables

Global variables are known throughout the module and their value is retained for the duration of the program run.

Local variables are only known in the subroutine or function that they are declared in. Their value is retained only while the subroutine or function is running and is lost each time the subroutine (etc) finishes executing.

Format

Option Compare Database
Option Explicit
 
Const global-constant As data-type = constant-expression 
Dim global-variable As data-type

Sub Main()
    Const local-constant As data-type = constant-expression
    Dim local-variable As data-type
    statement
    ...
End Sub

Sub sub-name(parameter As data-type, parameter As data-type,, ...) 
    Const local-constant As data-type = constant-expression
    Dim local-variable As data-type
    statement
    ...
End Sub 

Function function-name(parameter As data-type, parameter As data-type,, ...)
    Const local-constant As data-type = constant-expression
    Dim local-variable As data-type,
    statement
    ...
End Function

Written by Tim Whitfort