database design 2 vba reference - birkbeck, … design 2 vba reference 1. vba or macros? ... the...

22
Database Design 2 VBA Reference Database Design 2 VBA Reference 1. VBA or Macros?.............................................................................................................. 2 1.1 Advantages of VBA: ................................................................................................ 2 1.2 When to use macros................................................................................................ 3 1.3 From here... ............................................................................................................. 3 2. A simple event procedure ............................................................................................... 4 2.1 The code explained ................................................................................................. 4 2.2 How does the error handling work?......................................................................... 5 3. Procedures...................................................................................................................... 6 4. Modules .......................................................................................................................... 8 4.1 Class Modules ......................................................................................................... 8 4.2 Standard Modules ................................................................................................... 8 4.3 The Declarations Section ........................................................................................ 9 5. Variables ....................................................................................................................... 10 5.1 Declaring variables ................................................................................................ 10 5.2 Variable Scope and lifetime................................................................................... 10 5.3 Data types ............................................................................................................. 11 5.4 Variants ................................................................................................................. 11 5.5 Using the Option Explicit Statement ...................................................................... 11 6. Sub Statement .............................................................................................................. 13 7. Function Statement ....................................................................................................... 15 8. Events ........................................................................................................................... 17 8.1 Event Procedures .................................................................................................. 17 8.2 Responding to a click event by using an Event Procedure ................................... 17 9. Writing Code ................................................................................................................. 18 9.1 Adding comments and continuing a statement over multiple lines ....................... 18 9.2 Checking Syntax Errors ......................................................................................... 18 Declaration Statements .................................................................................................... 18 Assignment Statements ................................................................................................... 19 Executable Statements .................................................................................................... 20 10. Compiling Code ............................................................................................................ 22 d2vbaref.doc Page 1 of 22 05/11/02 14:21

Upload: duongdang

Post on 02-Apr-2018

232 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

Database Design 2 VBA Reference

1. VBA or Macros?.............................................................................................................. 2 1.1 Advantages of VBA: ................................................................................................ 2 1.2 When to use macros................................................................................................ 3 1.3 From here... ............................................................................................................. 3

2. A simple event procedure ............................................................................................... 4 2.1 The code explained ................................................................................................. 4 2.2 How does the error handling work?......................................................................... 5

3. Procedures...................................................................................................................... 6 4. Modules .......................................................................................................................... 8

4.1 Class Modules ......................................................................................................... 8 4.2 Standard Modules ................................................................................................... 8 4.3 The Declarations Section ........................................................................................ 9

5. Variables ....................................................................................................................... 10 5.1 Declaring variables ................................................................................................ 10 5.2 Variable Scope and lifetime................................................................................... 10 5.3 Data types ............................................................................................................. 11 5.4 Variants ................................................................................................................. 11 5.5 Using the Option Explicit Statement...................................................................... 11

6. Sub Statement .............................................................................................................. 13 7. Function Statement....................................................................................................... 15 8. Events ........................................................................................................................... 17

8.1 Event Procedures .................................................................................................. 17 8.2 Responding to a click event by using an Event Procedure ................................... 17

9. Writing Code ................................................................................................................. 18 9.1 Adding comments and continuing a statement over multiple lines ....................... 18 9.2 Checking Syntax Errors......................................................................................... 18 Declaration Statements .................................................................................................... 18 Assignment Statements ................................................................................................... 19 Executable Statements .................................................................................................... 20

10. Compiling Code ............................................................................................................ 22

d2vbaref.doc Page 1 of 22 05/11/02 14:21

Page 2: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

1. VBA or Macros? You can use either macros or VBA to automate your database. Macros are easier to learn to use and work well for simple tasks but VBA, the programming language supplied with Access, is more powerful and flexible. You need to learn to use VBA if you want to produce applications to a professional standard.

1.1 Advantages of VBA:

�� Easier maintenance The program code used with a form or report is part of that form or report. This means that if forms or reports are moved or copied to another database the code automatically goes with them. Macros are separate objects and need to be moved as well for the form or report to work correctly.

�� Create your own functions. You can create your own functions either to perform calculations that exceed the capability of an expression or to replace complex expressions. In addition, you can use the functions you create in expressions to apply a common operation to more than one object.

�� More flexible VBA gives you much more programmatic control. Code can run in response to user input and a wider selection of actions and arguments are available.

�� Executes faster Long, complex macros will execute considerably more slowly than the equivalent actions in VBA.

�� Easier to read and print You can only see one set of action arguments at a time in the macro window. This means you have to click on each action in turn to see all the details of the macro. In the VBA code window all the code is visible at the same time so it is much easier to read or print.

�� Mask error messages. If an unexpected error happens while a database is being used, the message displayed can often been confusing to the user. Using VBA, you can detect, trap and handle errors as they occur. By displaying an appropriate message, or writing code that takes an action, the user need not be aware that an error has taken place.

�� Create or manipulate objects. In most cases, you'll find that it's easiest to create and modify an object in that object's Design view. In some situations, however, you may want to manipulate the definition of an object in code. Using VBA, you can manipulate all the objects in a database, as well as the database itself.

�� Perform system-level actions. Using VBA, you can check to see if a file exists on the system, use Automation or dynamic data exchange (DDE) to communicate with other Windows-based applications such as Microsoft Excel, and call functions in Windows dynamic-link libraries (DLLs).

�� Manipulate records one at a time. You can use VBA to step through a set of records one record at a time and perform an operation on each record. In contrast, macros work with entire sets of records at once.

�� Pass arguments to your VBA procedures. You can pass arguments to your code at the time it is run or you can use variables for arguments - something you can't do in macros. This gives you a great deal of flexibility in how your Visual Basic procedures run.

��

d2vbaref.doc Page 2 of 22 05/11/02 14:21

Page 3: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

�� Integration with other Office applications You can use VBA to integrate your database with other applications such as Word and Excel.

1.2 When to use macros

�� Prototyping Macros are ideal as a prototype tool. They are an easy way to take care of simple details such as opening and closing forms, showing and hiding toolbars, and running reports. You can quickly and easily tie together the database objects you've created because there's little syntax to remember; the arguments for each action are displayed in the lower part of the Macro window.

�� Simple actions required to occur on a particular event, such as clicking on a command button, or a combo box, can be quickly and easily set-up

�� If you want actions to run whenever the database is opened you need to use the AutoExec macro. However much of the functionality of this has now been replaced by the Startup options (Tools menu). If you want VBA code to run when the database opens you can use the RunCode action in the Autoexec macro.

1.3 From here...

So you're convinced! You have to learn VBA. The following sections take you through some of the basics such as:.

�� How does VBA code actually work? (See Section 2)

�� What exactly is a procedure? (See Section 3)

�� Where is the code stored and what is the difference between a Class module and a standard module? See Section 4

�� What are variables and how do you use them? See (Section 5)

�� How do you write code? (See Section 9)

d2vbaref.doc Page 3 of 22 05/11/02 14:21

Page 4: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

2. A simple event procedure The following procedure is a typical piece of code that allows a user to create a new record. It is activated when a command button is pressed on an Access form.

Private Sub Add_Click() On Error GoTo Err_Add_Click

DoCmd.GoToRecord , , acNewRec

Exit_Add_Click:

Exit Sub

Err_Add_Click:

MsgBox Err.Description

Resume Exit_Add_Click

End Sub

2.1 The code explained

The Private Sub and End Sub lines designate the beginning and end of the procedure.

Add_click() is the name of the procedure. Note that it is followed by parentheses (brackets). Any arguments (see below) passed to the procedure would be inserted here. In the case of a procedure that doesn't take any arguments, as this example, the parentheses will be empty. The name will be used to call the procedure.

In between these two lines is the body of the procedure. This contains the instructions that are executed when the procedure is run.

The majority of code in this procedure relates to error handling. If there is not an error only the highlighted lines of code will execute.

The main action of this procedure is carried out by the line: DoCmd.GoToRecord , , AcNewrec

This tells Access to move to a new record. In order to understand how this line of code works, it is probably easiest to take it apart piece by piece.

Keyword : Each word that Access recognises as part of the VBA language is called a keyword (sometimes also known as a reserved word). These words have special meanings in VBA and you cannot be used for any other purpose (e.g naming variables see ........). Object: The first keyword in the line is DoCmd. DoCmd is an object. An object is something that knows how to perform actions. The DoCmd object knows how to perform common actions such as opening a form, printing a report or choosing a menu command.

You'll be using the DoCmd object a lot when you start to program with VBA.

Method: The second keyword is GoToRecord, which is a method of the DoCmd object. Methods are the actions that an object knows how to perform and each object has its own set of methods. The methods of the DoCmd object are all the actions it knows how to perform - if you've used macros you'll quickly notice that these are identical to the macro actions available in the Macro window. For example, the GoToRecord method has the action of telling Access to move to a specified record.

Arguments: Following the GoToRecord method are its arguments. The arguments provide any information required to carry out the method. For example, when you use the GoToRecord method you need to specify which record to move to. The argument list is separated from the method by a space, with a comma (,) between each argument in the list.

d2vbaref.doc Page 4 of 22 05/11/02 14:21

Page 5: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

Each method has a specified number of arguments, some of which are optional (you don't necessarily need to enter them). You must type the commas to indicate that optional arguments have been omitted unless they come at the end of the list.

GoToRecord method takes four arguments:

�� object type (e.g. form)*

�� object name (e.g. frmEmployees)*

�� which the record to move to. This is specified as a constant (see below).

�� the offset (distance from the current record)*

* omitted in this example.

Constant Values: Some methods, such as GoToRecord, have specially defined constant values (constants) that you can enter as arguments. Constants represent numbers, which is the type of argument the method expects in this position, but a name is much easier to remember and makes code more understandable. acNewRec is a constant with the value 5 that tells the GoToRecord Method to move to the new record at the end of the recordset.

Other constants that can be used with the GoToRecord method are:

�� acPrevious

�� acNext

�� acFirst

�� acLast

�� acGoTo

You should be able to work out what you'd expect each of these to do.

acGoTo instructs the method to move to a particular record but which record? If you use this argument you also need to use the fourth argument (offset) to specify the number of the record to move to. If you omit the fourth argument for acPrevious the method will move back one record but you can use it to specify a particular number of records. acNext works in a similar way but moves forward. The offset argument is not applicable to the other constants.

Now you should be able to see that in this line the first two arguments have been omitted meaning that the method will operate on the current object. The fourth argument has also been omitted but we don't need to indicate this with a comma as it is the last argument in the list. The third argument tells the method to move to the new record at the end of the recordset.

DoCmd.GoToRecord , , AcNewrec Once this line of code has been executed the procedure moves on to the next highlighted line of code:

Exit Sub

This has the effect of ignoring all the following lines of code and exiting from the procedure.

2.2 How does the error handling work?

The first line of code On Error GoTo Err_Add_Click tells the procedure what to do if there's an error. It instructs it to move to the section labelled Err_Add_Click: Notice that this line ends with a colon (:) meaning that it is a label rather than an instruction to be carried out. The procedure moves to this point in the code and then executes the following two instructions.

MsgBox Err.Description displays a message describing the error on the screen.

Resume Exit_Add_Click moves back to the line labelled Exit_Add_Click: which conveniently takes us back to the Exit Sub line so the procedure ends.

d2vbaref.doc Page 5 of 22 05/11/02 14:21

Page 6: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

3. Procedures A procedure is a unit of Visual Basic for Applications code. A procedure contains a series of statements and methods that perform an operation or calculate a value. For example, the following event procedure uses the OpenForm method to open the form:

Private Sub OpenOrders_Click()

DoCmd.OpenForm "Orders"

End Sub

There are two kinds of procedures:

Sub procedures perform an operation or series of operations but don't return a value. You can create your own Sub procedures or use the Access event procedure templates that are created for you.

Function procedures (often simply called functions) return a value, such as the result of a calculation. Visual Basic includes many built-in functions; for example, the Now() function returns the current date and time. In addition to these built-in functions, you can create your own custom functions.

Because functions return values, you can use them in expressions. You can use functions in expressions in many places in Access, including a VBA statement or method, in many property settings, or in a criteria expression in a filter or query.

Here is an example of a Function procedure, FirstOfNextMonth, that returns the date of the first day of the month following the current date:

Function FirstOfNextMonth()

FirstOfNextMonth =DateSerial(Year(Now), Month(Now) + 1, 1)

End Function

This custom function consists of a single assignment statement that assigns the results of an expression (on the right side of the equal sign [=]) to the name of the function, FirstOfNextMonth (on the left side of the equal sign). The function calculates a result using the built-in Visual Basic DateSerial, Year, Now, and Month functions.

Once you create this function, you can use it in an expression almost anywhere in Microsoft Access. For example, you could specify that a text box display the first day of the month following the current date as its default value by setting the text box control's DefaultValue property to the following expression in the property sheet:

=FirstOfNextMonth()

d2vbaref.doc Page 6 of 22 05/11/02 14:21

Page 7: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

Both Sub and Function procedures can accept arguments.

Function is a procedure, which accepts none or several arguments and returns a value, which can be used in an expression (Example: NoDays(month) 'returns number of days in a given month)

Sub is a procedure, which accepts none, or several arguments but which cannot be used in any expression.

All executable code must be in Sub or Function procedures. You can't define a Sub procedure inside another Sub or Function procedure.

More about Sub procedures (Section 6)

More about Function procedures (Section 7)

d2vbaref.doc Page 7 of 22 05/11/02 14:21

Page 8: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

4. Modules All VBA code is stored in Modules. There are two types:

Class Modules contain code that is associated with a particular form or report and the code in them can only be run from that form or report.

Standard Modules contain general purpose procedures that can be run from anywhere within your database.

Procedures in your form and report modules can call procedures you have added to standard modules.

4.1 Class Modules

Form and report modules are class modules that are associated with a particular form or report. They often contain event procedures that run in response to an event on the form or report. You can use event procedures to control the behaviour of your forms and reports, and their response to user actions such as clicking the mouse on a command button.

When you create the first event procedure for a form or report, Microsoft Access automatically creates an associated form or report module. To see the module for a form or report, change

to Design view and click the Code button on the toolbar or Select Code from the View Menu.

Hint: You can also use ALT + F11 to switch between the database and code windows.

Procedures stored in module of selected object List of objects that have modules

associated with them

4.2 Standard Modules

Standard modules contain general procedures that aren't associated with any particular object. They are useful for frequently used procedures that can be run from anywhere within your database.

To view the list of standard modules in your database click the Modules Object in the Database window. You can open an existing module to view, modify or add to the code by clicking the Design button on the toolbar. To create a new module, click the New button. This opens the Code window with a new module window for you to enter code into.

d2vbaref.doc Page 8 of 22 05/11/02 14:21

Page 9: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

Code for existing module

List of Standard Modules in your database

Window to enter code for new module

4.3 The Declarations Section

The Declarations section contains the Option Compare Database statement, and can also contain other statements. The declarations section is the topmost level of a module that appears before any Sub or Function procedures. This section contains definitions of user-defined data types, global constants, and global variables.

To display the Declarations section, select (declarations) in the Procedure box in the Module window:

d2vbaref.doc Page 9 of 22 05/11/02 14:21

Page 10: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

5. Variables A variable is a named storage location that can contain data that can be modified during program execution. Each variable has a name that uniquely identifies it within its level of scope. A data type can be specified or not.

You can refer to data and objects directly in your code, or declare object variables to represent them. Once an object variable is declared and assigned, you can use it just as you would the name of the object it represents, and you can change its value, just as you can change the value of any variable.

5.1 Declaring variables

When declaring variables you usually use the Dim <variable name> statement. For example: Dim dbs As Database, tbl As TableDef, fld As Field

The statement above declares three variables, a Database object named dbs, a TableDef object named tbl and a Field object named fld.

Rules for Variable Names �� Must start with a letter.

�� Can only contain letters, numbers and underscores ([Shift]+[-]).

�� Cannot be longer than 40 characters.

�� Cannot be reserved words.

�� Avoid using spaces in variable names because most other DBMS systems will not accept names with spaces.

5.2 Variable Scope and lifetime

The scope of a variable refers to its visibility, that is, where it can be seen. The value of a variable can only be changed when it is in scope.

A variable that is declared within a procedure has local scope. Its value can only be referred to or changed from within that procedure.

Variables can also be declared the Declarations section at the top of a module. These module-level variables can be seen and used by all procedures in that module and are said to have public scope.

The lifetime of a variable means how long it can be seen for, or how long it is in scope. Local variables only exist while their procedure is running. Once the procedure finishes their value is lost. The next time that the procedure is called the local variables are recreated.

To create a variable that retains its value between procedure calls you must declare it as Static as in the following statement:

Static intNum As Integer A variable declared in this way is only in scope when the procedure in which it is declared is running but it retains its value between calls to the procedure. This can be useful if, for example, you want to increment a counter each time a procedure is called. Module-level variables are available to all procedures within the module, but not to procedures in other modules in the project. To make them available to all procedures in the project, they must be declared as Public, as in the following statement:

d2vbaref.doc Page 10 of 22 05/11/02 14:21

Page 11: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

Public strName As String

A variable declared in this way exists as long as the database is open and can be used by all procedures in the database.

5.3 Data types

Variables can be declared as one of the following data types:

�� Boolean

�� Byte

�� Integer

�� Long

�� Currency

�� Single

�� Double

�� Date

�� String (for variable-length strings)

�� String * length (for fixed-length strings

�� Object

�� Variant

If you do not specify a data type, the Variant data type is assigned by default. You can also create a user-defined type using the Type statement.

5.4 Variants

The Variant data type is automatically specified if you don't specify a data type when you declare a constant, variable, or argument. Variables declared as the Variant data type can contain string, date, time, Boolean, or numeric values, and can convert the values they contain automatically. Numeric Variant values require 16 bytes of memory (which is significant only in large procedures or complex modules) and they are slower to access than explicitly typed variables of any other type. You rarely use the Variant data type for a constant. String Variant values require 22 bytes of memory.

The following statements create Variant variables:

Dim myVar

Dim yourVar As Variant

theVar = "This is some text."

The last statement does not explicitly declare the variable theVar, but rather declares the variable implicitly, or automatically. Variables that are declared implicitly are specified as the Variant data type.

5.5 Using the Option Explicit Statement

You can implicitly declare a variable in Visual Basic simply by using it in an assignment statement. All variables that are implicitly declared are of type Variant. Variables of type Variant require more memory resources than most other variables. Your application will be

d2vbaref.doc Page 11 of 22 05/11/02 14:21

Page 12: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

more efficient if you declare variables explicitly and with a specific data type. Explicitly declaring all variables reduces the incidence of naming-conflict errors and spelling mistakes.

If you don't want Visual Basic to make implicit declarations, you can place the Option Explicit statement in a module before any procedures. This statement requires you to explicitly declare all variables within the module. If a module includes the Option Explicit statement, a compile-time error will occur when Visual Basic encounters a variable name that has not been previously declared, or that has been spelled incorrectly.

This example uses the Option Explicit statement to force you to explicitly declare all variables. Attempting to use an undeclared variable causes an error at compile time. The Option Explicit statement is used at the module level only.

Option explicit ' Force explicit variable declaration.

Dim MyVar ' Declare variable.

MyInt = 10 ' Undeclared variable generates error.

MyVar = 10 ' Declared variable does not generate error.

d2vbaref.doc Page 12 of 22 05/11/02 14:21

Page 13: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

6. Sub Statement The sub statement declares the name, arguments, and code that form the body of a Sub procedure.

The Sub statement syntax has these parts:

Part Description

Public Optional. Indicates that the Sub procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private statement, the procedure is not available outside the project.

Private Optional. Indicates that the Sub procedure is accessible only to other procedures in the module where it is declared.

Static Optional. Indicates that the Sub procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Sub, even if they are used in the procedure.

name Required. Name of the Sub; follows standard variable naming conventions.

arglist Optional. List of variables representing arguments that are passed to the Sub procedure when it is called. Multiple variables are separated by commas.

d2vbaref.doc Page 13 of 22 05/11/02 14:21

Page 14: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

statements Optional. Any group of statements to be executed within the Sub procedure.

d2vbaref.doc Page 14 of 22 05/11/02 14:21

Page 15: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

7. Function Statement The function statement declares the name, arguments, and code that form the body of a Function procedure.

The Function statement syntax has these parts:

Part Description

Public Optional. Indicates that the Function procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private, the procedure is not available outside the project.

Private Optional. Indicates that the Function procedure is accessible only to other procedures in the module where it is declared.

Static Optional. Indicates that the Function procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Function, even if they are used in the procedure.

name Required. Name of the Function; follows standard variable naming conventions.

arglist Optional. List of variables representing arguments that are passed to the Function procedure when it is called. Multiple variables are separated by commas.

type Optional. Data type of the value returned by the Function procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String, or (except fixed length), Object, Variant or any user defined type Arrays of any type can't be returned

d2vbaref.doc Page 15 of 22 05/11/02 14:21

Page 16: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

but a Variant containing an array can.

statements Optional. Any group of statements to be executed within the Function procedure.

expression Optional. Return value of the Function.

d2vbaref.doc Page 16 of 22 05/11/02 14:21

Page 17: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

8. Events An event is a specific action that occurs on or with a certain object. Microsoft Access can respond to a variety of events: mouse clicks, changes in data, forms opening or closing, and many others. Events are usually the result of user action.

Using either an event procedure or a macro, you can add your own custom response to an event that occurs on a form, report, or control.

8.1 Event Procedures

The Code Builder displays the Module window, in which you create or modify an event procedure from within an event property of a form, report, section, or control.

An event procedure is a Sub procedure which is invoked automatically in response to an event.

To create an event procedure, you must first determine the event (for example, a mouse click or updating a record) whose event property will trigger the event procedure.

Event procedures are stored with the form or report module they were created in.

8.2 Responding to a click event by using an Event Procedure

When you create an event procedure for an object, Microsoft Access adds an event procedure template named for the event and the object to the form or report module. All you need to do is add code that responds in the way you want when the event occurs for the form or report.

d2vbaref.doc Page17 of 22 05/11/02 14:21

Page 18: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

9. Writing Code A statement in Visual Basic is a complete instruction. It can contain:

�� Keywords

�� Operators

�� Variables

�� Constants

�� Expressions.

Each statement belongs to one of the following three categories:

Declaration statements, which name a variable, constant, or procedure and can also specify a data type.

Assignment statements, which assign a value or expression to a variable or constant.

Executable statements, which initiate actions. These statements can execute a method or function, and they can loop or branch through blocks of code. Executable statements often contain mathematical or conditional operators.

9.1 Adding comments and continuing a statement over multiple lines

Comments can explain a procedure or a particular instruction to anyone reading your code. Comment lines begin with an apostrophe (') or with Rem followed by a space, and can be added anywhere in a procedure. By default, comments are displayed as green text. A long statement can be continued onto the next line using a line-continuation character ( _ )

Sub TestBox() 'This procedure declares a string variable, assigns it the value John, and then displays a message.

Dim myVar As String

myVar = "John"

MsgBox Prompt:="Hello " & myVar, Title:="Greeting Box", _

Buttons:=vbExclamation

End Sub

9.2 Checking Syntax Errors

If you press ENTER after typing a line of code and the line is displayed in red (an error message may display as well), you must find out what's wrong with your statement, and then correct it.

Extra Information - Writing Code

Declaration Statements

d2vbaref.doc Page18 of 22 05/11/02 14:21

Page 19: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

You use declaration statements to name and define procedures, variables, arrays, and constants. When you declare a procedure, variable, or constant, you also define its scope, depending on where you place the declaration and what keywords you use to declare it.

The following example contains three declarations.

Sub ApplyFormat()

Const limit As Integer = 33

Dim myCell As Range

' More statements

End Sub

The Sub statement (with matching End Sub statement) declares a procedure named ApplyFormat. All the statements enclosed by the Sub and End Sub statements are executed whenever the ApplyFormat procedure is called or run.

The Const statement declares the constant limit, specifying the Integer data type and a value of 33.

The Dim statement declares the variable myCell. The data type is an object, in this case, a Microsoft Excel Range object. You can declare a variable to be any object that is exposed in the application you are using.

Dim statements are one type of statement used to declare variables.

Other keywords used in declarations are ReDim, Static, Public, Private, and Const.

Assignment Statements

Assignment statements assign a value or expression to a variable or constant. Assignment statements always include an equal sign (=). The following example assigns the return value of the InputBox function to the variable yourName.

Sub Question()

Dim yourName As String

yourName = InputBox("What is your Name?")

MsgBox "Your name is " & yourName

End Sub

The Let statement is optional and is usually omitted. For example, the preceding assignment statement can be written

Let yourName = InputBox("What is your name?"). The Set statement is used to assign an object to a variable that has been declared as an object. The Set keyword is required. In the following example, the Set statement assigns a range on Sheet1 to the object variable myCell:

Sub ApplyFormat()

d2vbaref.doc Page19 of 22 05/11/02 14:21

Page 20: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

Dim myCell As Range

Set myCell = Worksheets("Sheet1").Range("A1")

With myCell.Font

.Bold = True

.Italic = True

End With

End Sub

Statements that set property values are also assignment statements. The following example sets the Bold property of the Font object for the active cell:

ActiveCell.Font.Bold = True

Executable Statements

An executable statement initiates action. It can execute a method or function, and it can loop or branch through blocks of code. Executable statements often contain mathematical or conditional operators.

The following example uses a For Each...Next statement to iterate through each cell in a range named MyRange on Sheet1 of an active Microsoft Excel workbook. The variable c is a cell in the collection of cells contained in MyRange.

Sub ApplyFormat()

Const limit As Integer = 33

For Each c In Worksheets("Sheet1").Range("MyRange").Cells

If c.Value > limit Then

With c.Font

.Bold = True

.Italic = True

End With

End If

Next c

MsgBox "All done!"

End Sub

d2vbaref.doc Page20 of 22 05/11/02 14:21

Page 21: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

�� The If...Then...Else statement in the example checks the value of the cell. If the value is greater than 33, the With statement sets the Bold and Italic properties of the Font object for that cell. If...Then...Else statements end with End If.

�� The With statement can save typing because the statements it contains are automatically executed on the object following the With keyword.

�� The Next statement calls the next cell in the collection of cells contained in MyRange.

�� The MsgBox function (which displays a built-in Visual Basic dialog box) displays a message indicating that the Sub procedure has finished running.

d2vbaref.doc Page21 of 22 05/11/02 14:21

Page 22: Database Design 2 VBA Reference - Birkbeck, … Design 2 VBA Reference 1. VBA or Macros? ... The methods of the DoCmd object are all the actions it knows how to perform - if

Database Design 2 VBA Reference

10. Compiling Code

As you create your procedures, you will notice how Access checks each line of code you enter to make sure that it doesn't contain any errors. However, many errors are not obvious in a single line. To see them, you have to look at the line of code in the context of the rest of the procedure or application.

Although it does not do so automatically while you enter code, Access does check your procedures before you run them. It checks for various types of consistency (e.g. whether the variables you have used in your code are all declared, and whether the procedures you call exist in your application). This process is called compiling.

One way to compile a procedure is to try running it. But this is not a very efficient method to use and you can therefore ask Access to compile your procedures at any time. To do this you select Compile from the Debug menu.

d2vbaref.doc Page22 of 22 05/11/02 14:21