ELA NOTES - MS Access & Visual Basic
Alphabetical, by Type, or go to Text
(
also see.. Examples )
INDEX - ALPHABETICAL
A |
C|
D |
E |
F |
I |
L |
N |
O |
P |
Q |
R |
S |
T |
U |
V |
W |
Action Const |
Action Property OLE Property |
Activate, Deactivate Event |
Add Method |
AddFromFile Method |
Append Method (DAO) |
Append Query SQL |
AppendTable Access |
Application Object |
ApplyFilter Action |
ApplyFilter Method |
Arguments, Understanding |
Array as Query Destination SQL |
Arrays, Using |
AutoKeys MACRO |
Call Statement |
Change Event |
Close Action |
Close Method |
Collection Object |
Combo Box Control |
ComboBox Properties |
CONSTRAINT SQL |
Copy Table Structure Access |
Copy Table Structure SQL |
CreateField Method |
CREATE INDEX SQL |
CreateQueryDef Method |
CREATE TABLE SQL |
CreateWorkspace Method |
CurrentDb Function |
Data Access Objects & Collections Reference Object |
DAO Const |
Data Type Property |
DecimalPlaces Property |
Declaring Arrays |
DoCmd Object |
DoMenuItem Method |
Dynaset-type Recordset |
Enumerated Const-Acc97 |
Entering.. Expressions |
Filter Property |
Find Data |
FindNext Action |
FindNext Method |
FindRecord Action |
FindRecord Method |
ForEach...Next Statement |
Format Function |
Format Property |
Format Query |
Formats - User Defined |
Function, Create a custom..
Function Statement Access 97 |
Function Statement General |
IIf Function |
IN Clause SQL |
In Operator SQL |
INSERT INTO SQL |
Item Method |
List Box Control |
List Box Control Properties |
Load, Unload Event |
NewCurrentDatabase Method |
Nothing Keyword |
Null values in Calculated Fields |
Nz Function |
Open, Close Event |
OpenDatabase METHOD |
OpenForm Action |
OpenForm Method |
OpenQuery Action |
OpenQuery Method |
OpenRecordset Method |
OpenReport Action |
OpenTable Action |
OpenTable Method |
Overview Const-Access |
Parameters: - also see
Arguments |
Parameter Arrays, Understanding Arrays |
Parameter Object |
PARAMETERS Declaration SQL |
ProjectName Property |
Query, Action SQL |
Query-Parameter SQL |
QueryDef Object |
RecordCount |
Reference Object |
Remove Method |
Requery Method |
Run Method |
RunCode Action |
RunCommand Const |
RunCommand Method |
RunSQL Action |
RunSQL Method |
Selected Property |
SELECT SQL Statement |
SELECT...INTO SQL Statement |
SendKeys Statement |
Set Statement |
SetFocus Method |
Set to Type Libraries References |
Snapshot-type Recordset |
Subqueries SQL |
Subquery in a Calculated Field SQL |
Table-type Recordset |
Text Property |
Type Property (DAO) |
Type Conversion Functions |
UNION Operation SQL Operation |
UPDATE SQL Statement |
Value Property |
Variable Type Const- VB |
WHERE Clause SQL Clause |
Workspace Object |
CONTENT BY TYPE
ACCESS |
ACTIONS |
CONSTANTS |
CONTROLS |
EVENTS |
EXPRESSIONS |
Format |
FUNCTIONS |
MACROS |
METHODS |
Null |
OBJECTS |
OLE |
PARAMETERS |
PROCEDURES |
PROPERTIES |
RECORDSETS |
REFERENCES |
SQL |
STATEMENTS
ACCESS
AppendTable |
Copy Table Structure |
ACTIONS
ApplyFilter |
Close |
FindNext |
FindRecord |
OpenForm |
OpenQuery |
OpenReport |
OpenTable |
RunCode |
RunSQL |
ARRAYS
Declaring |
Parameter Arrays, Understanding |
Using |
CONSTANTS
Overview (Access)
Action |
DAO |
Enumerated, Acc97 |
RunCommand |
Variable Type VB |
CONTROLS
Combo Box |
List Box |
DATA
Find |
EVENTS
Activate, Deactivate |
Change |
Load, Unload |
Open, Close |
EXPRESSIONS
Entering.. |
Formats
Query |
User Defined |
FUNCTIONS
Create a custom.. |
CurrentDb Function |
Format |
Function Statement (Access 97) |
Function Statement(General) |
IIf |
Nz |
Type Conversion |
MACROS
AutoKeys
KEYWORDS
Nothing
METHODS
Add |
AddFromFile |
Append (DAO) |
ApplyFilter |
Close |
CreateField |
CreateQueryDef |
CreateWorkspace |
DoMenuItem
FindNext |
FindRecord |
Item |
NewCurrentDatabase |
OpenDatabase |
OpenForm |
OpenQuery |
OpenRecordset |
OpenTable
Remove |
Requery |
Run |
RunCommand
|
RunSQL |
SetFocus |
Null values in Calculated Fields
OBJECTS
Application |
Collection |
Data Access Objects & Collections Ref |
DoCmd |
Parameter |
QueryDef |
Reference |
Workspace |
OLE
Action Property
PARAMETERS
Query |
PROCEDURES
Arguments, Understanding |
PROPERTIES
ComboBox |
Data Type Property |
DecimalPlaces Property |
Filter |
Format |
List Box Control |
ProjectName |
RecordCount |
Selected |
Text |
Type (DAO) |
Value
RECORDSETS
Dynaset-type |
Snapshot-type |
Table-type
REFERENCES
Set to Type Libraries
SQL
Array as Query Destination |
Copy Table Structure |
Query-Action |
Query-Append |
Query-Parameter |
Subqueries |
Subquery in a Calculated Field |
SQL STATEMENTS
CONSTRAINT |
CREATE INDEX |
CREATE TABLE |
IN Clause |
In Operator |
INSERT INTO |
PARAMETERS Declaration |
SELECT |
SELECT...INTO |
UNION Operation |
UPDATE |
WHERE Clause
STATEMENTS
Call |
ForEach...Next |
SendKeys |
Set
ACCESS - Append Table
see..Append Query
ACCESS - Copy Table Structure
In the Database window Copy the Table using the Edit Menu, Right-Click shortcut Menu,
the Control-C keyboard shortcut keys. When the table is pasted (using the same menus or
Control-V shortcut keys, a "Paste Table As" dialog will appear. Choose the "Structure
Only" option. This will copy the structure of the table only, without any data. The
data may also be appended to another table using the "Append Data to Existing Table"
option.
ACTION - ApplyFilter
You can use the ApplyFilter action to apply a filter, a query, or an SQL WHERE clause to a table, form, or report to restrict or sort the records in the table, or the records from the underlying table or query of the form or report. For reports, you can use this action only in a macro specified by the report's OnOpen event property.
Setting
The ApplyFilter action has the following arguments.
Action argument Description
Filter Name The name of a filter or query that restricts or sorts the records of the table, form, or report. You can enter the name of either an existing query or a filter that has been saved as a query in the Filter Name box in the Action Arguments section of the Macro window.
Where Condition A valid SQL WHERE clause (without the word WHERE) or an expression that restricts the records of the table, form or report.
Note In a Where Condition argument expression, the left side of the expression typically contains a field name from the underlying table or query for the form or report. The right side of the expression typically contains the criteria you want to apply to this field in order to restrict or sort the records. For example, the criteria can be the name of a control on another form that contains the value you want the records in the first form to match. The name of the control should be fully qualified, for example:Forms!formname!controlname
The maximum length of the Where Condition argument is 256 characters. If you need to enter a longer SQL WHERE clause, use the ApplyFilter method of the DoCmd object in Visual Basic. You can enter SQL WHERE clause statements of up to 32,768 characters in Visual Basic.
Note You must use one or both arguments. You can use the Filter Name argument if you've already defined a filter that provides the appropriate data. You can use the Where Condition argument to enter the restriction criteria directly. If you use both arguments, Microsoft Access applies the WHERE clause to the results of the filter.
Remarks
You can apply a filter or query to a form in Form view or Datasheet view.
The filter and WHERE condition you apply become the setting of the form's or report's Filter property.
For tables and forms, this action is similar to clicking Apply Filter/Sort on the Records menu or clicking Apply Filter on the toolbar. The menu command or button applies the most recently created filter to the table or form, whereas the ApplyFilter action applies a specified filter or query.
If you point to Filter on the Records menu and then click Advanced Filter/Sort after running the ApplyFilter action, the Advanced Filter/Sort window shows the filter criteria you've selected with this action.
To remove a filter and display all of the records for a table or form, you can use the ShowAllRecords action, the Remove Filter/Sort command on the Records menu, or Remove Filter on the toolbar.
When you save a table or form, Microsoft Access saves any filter currently defined in that object, but won't apply the filter automatically the next time the object is opened (although it will automatically apply any sort you applied to the object before it was saved). If you want to apply a filter automatically when a form is first opened, specify a macro containing the ApplyFilter action or an event procedure containing the ApplyFilter method of the DoCmd object as the OnOpen event property setting of the form. You can also apply a filter by using the OpenForm or OpenReport action, or their corresponding methods. To apply a filter automatically when a table is first opened, you can open the table by using a macro containing the OpenTable action, followed immediately by the ApplyFilter action.
ACTION - Close
You can use the Close action to close either a specified Microsoft Access window or the
active window if none is specified.
Setting
The Close action has the following arguments.
Action argument Description
Object Type The type of object whose window you want to close. Click Table,
Query, Form, Report, Macro, or Module in the Object Type box in
the Action Arguments section of the Macro window. To select the
active window, leave this argument blank.
Object Name The name of the object to be closed. The Object Name box shows all
objects in the database of the type selected by the Object Type
argument. Click the object to close. If you leave the Object Type
argument blank, leave this argument blank also.
Save Whether to save changes to the object when it's closed. Click Yes
(save the object), No (close the object without saving it), or
Prompt (prompt the user whether or not to save the object). The
default is Prompt.
Remarks
The Close action works on all database objects that the user can explicitly open or
close. This action has the same effect as selecting an object and then closing it by
clicking Close on the File menu, clicking Close on the Control menu for the object's
window, or clicking the Close button for the object.
If the Save argument is set to Prompt and the object hasn't already been saved before
the Close action is carried out, a dialog box prompts the user to save the object before
the macro closes it. If you've set the Warnings On argument of the SetWarnings action to
No, the dialog box isn't displayed and the object is automatically saved.
To run the Close action in Visual Basic, use the Close method of the DoCmd object.
ACTION - FindNext
You can use the FindNext action to find the next record that meets the criteria specified
by the previous FindRecord action or the Find In Field dialog box, available by clicking
Find on the Edit menu. You can use the FindNext action to search repeatedly for records.
For example, you can move successively through all the records for a specific customer.
Setting
The FindNext action doesn't have any arguments. The FindNext action finds the next record
that meets the criteria set either by the FindRecord action or in the Find In Field dialog
box. The arguments for the FindRecord action are shared with the options in the Find In
Field dialog box.
To set the search criteria, use the FindRecord action. Typically, you enter a FindRecord
action in a macro and then use the FindNext action to find succeeding records that meet
the same criteria. To search for records only when a certain condition is met, you can enter
a conditional expression in the Condition column of the action row for the FindNext action.
Remarks
This action has the same effect as using the Find Next button in the Find In Field
dialog box.
Note
While the FindRecord action corresponds to the Find command on the Edit menu for tables,
queries, and forms, it doesn't correspond to the Find command on the Edit menu in the
Module window. You can't use the FindRecord action or FindNext action to search for text
in modules.
Tip
If you've set the Only Current Field argument of the FindRecord action to Yes, you may
need to use the GoToControl action to move the focus to the control containing the data
you're searching for before you use the FindNext action.
Microsoft Access 97 and Microsoft Access 95 behave differently from earlier versions in
regard to where the FindNext macro action begins the search for the next instance of the
search criteria. In earlier versions of Microsoft Access, the search always begins starting
with the next record in the recordset. Starting with Microsoft Access 95, if the currently
selected text is the same as the search text at the time the FindNext macro action is
carried out, the search begins immediately following the selection in the same field as
the selection, and in the same record. Otherwise the search begins at the start of the
current record. This enables you to find multiple instances of the same search criteria that
might appear in a single record, whereas in Microsoft Access version 2.0, you are limited to
finding only the first instance of the search criteria in a record.
However, note that if you use a command button to run a macro containing the FindNext
action, the first instance of the search criteria will be found repeatedly. This is because
clicking the command button changes the focus from the field containing the matching value.
The FindNext action will then begin searching from the start of the record. The first
instance of the search criteria will be found repeatedly in the same record. To avoid this
problem, run the macro by using a technique that doesn't change the focus, such as a custom
toolbar button or a key combination defined in an AutoKeys macro, or in the macro set the
focus to the field containing the search criteria before you carry out the FindNext action.
The same behavior also occurs if you use a command button to run a macro containing the
FindRecord action with the Find First argument set to No. For information about how the
FindNext action searches for records, search the Microsoft Knowledge Base for article
Q150665, "FindNext Does Not Advance To Next Record To Search." To link to the Microsoft
Access Knowledge Base search page, click . For information on accessing the Knowledge
Base or other online technical resources, see Connect to Microsoft technical resources.
To run the FindNext action in Visual Basic, use the FindNext method of the DoCmd object.
ACTION - FindRecord
You can use the FindRecord action to find the first instance of data that meets the
criteria specified by the FindRecord arguments. This can be in the current record, in
a succeeding or prior record, or in the first record. You can find records in the active
table datasheet, query datasheet, form datasheet, or form.
Setting
The FindRecord action has the following arguments.
Action argument Description
Find What Specifies the data you want to find in the record. Enter the text,
number, or date you want to find or type an expression, which is
preceded by an equal sign (=), in the Find What box in the Action
Arguments section of the Macro window. You can use wildcard
characters. This is a required argument.
Match Specifies where the data is located in the field. You can specify
a search for data in any part of the field (Any Part Of Field), for
data that fills the entire field (Whole Field), or for data located
at the beginning of the field (Start Of Field). The default is
Whole Field.
Match Case Specifies whether the search is case-sensitive (uppercase and
lowercase letters must match exactly). Click Yes (conduct a
case-sensitive search) or No (search without matching uppercase
and lowercase letters exactly). The default is No.
Search Specifies whether the search proceeds from the current record
up to the beginning of the records (Up); down to the end of the
records (Down); or down to the end of the records and then from
the beginning of the records to the current record, so all records
are searched (All). The default is All.
Search As Formatted Specifies whether the search includes formatted data. Click Yes
(Microsoft Access searches for the data as it's formatted and
displayed in the field) or No (Microsoft Access searches for the
data as it's stored in the database, which isn't always the same
as it's displayed). The default is No.You can use this feature to
restrict the search to data in a particular format. For example,
click Yes and enter 1,234 in the Find What argument to find a value
of 1,234 in a field formatted to include commas. Click No if you
want to enter 1234 to search for the data in this field.To search
for dates, click Yes to find a date exactly as it's formatted,
such as 03-March-1991. If you click No, enter the date in the Find
What argument in the format set in the Regional Settings Properties
dialog box in Windows Control Panel. (This is the Short Date Style
box found on the Date tab of the Regional Settings Properties dialog
box.) For example, if the Short Date Style box is set to M/d/yy, you
can enter 3/9/91, and Microsoft Access will find all entries in a
Date field that correspond to March 9, 1991, regardless of how this
field is formatted.Note This argument takes effect only if the
current field is a bound control, the Match argument is set to Whole
Field, the Only Current Field argument is set to Yes, and the Match
Case argument is set to No.If you set Match Case to Yes or Only
Current Field to No, you must also set Search As Formatted to Yes.
Only Current Field Specifies whether the search is confined to the current field in
each record or includes all fields in each record. The current field
search is faster. Click Yes (confine the search to the current field)
or No (search in all fields in each record). The default is Yes.
Find First Specifies whether the search starts at the first record or at the
current record. Click Yes (start at the first record) or No (start
at the current record). The default is Yes.
Remarks
When a macro runs the FindRecord action, Microsoft Access searches for the specified data
in the records (the order of the search is determined by the setting of the Search argument).
When Microsoft Access finds the specified data, the data is selected in the record.
The FindRecord action is equivalent to clicking Find on the Edit menu, and its arguments are
the same as the options in the Find In Field dialog box, available by clicking Find on the
Edit menu. If you set the FindRecord arguments in the Macro window and then run the macro,
you'll see the corresponding options selected in the Find In Field dialog box when you click
Find.
Microsoft Access retains the most recent FindRecord arguments during a database session so
that you don't need to enter the same criteria repeatedly as you perform subsequent
FindRecord operations. If you leave an argument blank, Microsoft Access uses the most
recent setting for the argument, as set either by a previous FindRecord action or in the
Find In Field dialog box.
When you want to find a record by using a macro, use the FindRecord action, not the
RunCommand action with its argument set to run the Find command.
Note While the FindRecord action corresponds to Find on the Edit menu for tables, queries,
and forms, it doesn't correspond to Find on the Edit menu in the Module window. You can't
use the FindRecord action to search for text in modules.
Microsoft Access 97 and Microsoft Access 95 behave differently from earlier versions in
regard to where the FindRecord macro action begins the search for the next instance of the
search criteria when the Find First argument is set to No. In versions of Microsoft Access
prior to Microsoft Access 95, the search always begins starting with the next (previous or
succeeding) record in the recordset. Starting with Microsoft Access 95, if the currently
selected text is the same as the search text at the time the FindRecord macro action is
carried out, the search begins immediately following the selection in the same field as the
selection, and in the same record. Otherwise the search begins at the start of the current
ingle record, whereas in Microsoft Access version 2.0, you are limited to finding only the
first instance of the search criteria in a record.
However, note that if you use a command button to run a macro containing the FindRecord
action, the first instance of the search criteria will be found repeatedly. This is because
clicking the command button changes the focus from the field containing the matching value.
The FindRecord action will then begin searching from the start of the record. The first
instance of the search criteria will be found repeatedly in the same record. To avoid this
on or a key combination defined in an AutoKeys macro, or in the macro set the focus to the
field containing the search criteria before you carry out the FindRecord action.
The same behavior also occurs if you use a command button to run a macro containing the
FindNext action. For information about how the FindNext action searches for records, search
the Microsoft Knowledge Base for article Q150665, "FindNext Does Not Advance To Next Record
To Search." To link to the Microsoft Access Knowledge Base search page, click . For
information on accessing the Knowledge Base or other online technical resources, see Connect
to Microsoft technical resources.
To run the FindRecord action in Visual Basic, use the FindRecord method of the DoCmd object.
ACTION - OpenForm
You can use the OpenForm action to open a form in Form view, form Design view, Print
Preview, or Datasheet view
You can select data entry and window modes for the form and restrict the records that
the form displays.
Setting
The OpenForm action has the following arguments.
Argument Description
Form Name The name of the form to open. The Form Name box in the Action Arguments
section of the Macro window shows all forms in the current database. This
is a required argument.If you run a macro containing the OpenForm action
in a library database, Microsoft Access looks for the form with this name
first in the library database, then in the current database.
View The view in which the form will open. Click Form, Design, Print Preview,
or Datasheet in the View box. The default is Form.
Note The View argument setting overrides the settings of the form's DefaultView
and ViewsAllowed properties. For example, if a form's ViewsAllowed property
is set to Datasheet, you can still use the OpenForm action to open the form
in Form view.
Filter Name A filter that restricts or sorts the form's records. You can enter the name
of either an existing query or a filter that was saved as a query. However,
the query must include all the fields in the form you are opening or have
its OutputAllFields property set to Yes.
Where Condition A valid SQL WHERE clause (without the word WHERE) or expression that
Microsoft Access uses to select records from the form's underlying table or
query. If you select a filter with the Filter Name argument, Microsoft Access
applies this WHERE clause to the results of the filter. To open a form and
restrict its records to those specified by the value of a control on another
form, use the following expression:
[fieldname] = Forms![formname]![controlname on other form]
The fieldname argument is the name of a field in the underlying table or
query of the form you want to open. The controlname on other form argument
is the name of the control on the other form that contains the value you want
records in the first form to match.
Note
The maximum length of the Where Condition argument is 256 characters. If
you need to enter a more complex SQL WHERE clause longer than this, use the
OpenForm method of the DoCmd object in Visual Basic instead. You can enter
SQL WHERE clause statements of up to 32,768 characters in Visual Basic.
Data Mode The data entry mode for the form. This applies only to forms opened in Form
view or Datasheet view. Click Add (the user can add new records but can't
edit existing records), Edit (the user can edit existing records and add new
records), or Read Only (the user can only view records). The default is Edit.
Notes
The Data Mode argument setting overrides the settings of the form's
AllowEdits, AllowDeletions, AllowAdditions, and DataEntry properties. For
example, if a form's AllowEdits property is set to No, you can still use
the OpenForm action to open the form in Edit mode.· If you leave this
argument blank, Microsoft Access opens the form in the data entry mode set
by the form's AllowEdits, AllowDeletions, AllowAdditions, and DataEntry
properties.
Window Mode The window mode in which the form opens. Click Normal so the form is in the
mode set by its properties, Hidden (the form is hidden), Icon (the form opens
minimized as a small title bar at the bottom of the screen), or Dialog (the
form's Modal and PopUp properties are set to Yes). The default is Normal.
Remarks
This action is similar to clicking the Open button or Design button in the Database window
after selecting a form on the Forms tab.
A form can be modal (it must be closed or hidden before the user can perform any other action)
or modeless (the user can move to other windows while the form is open). It can also be a
pop-up form (a form used to collect or display information that remains on top of all other
Microsoft Access windows). You set the Modal and PopUp properties when you design the form.
If you use Normal for the Window Mode argument, the form opens in the mode specified by these
property settings. If you use Dialog for the Window Mode argument, these properties are both
set to Yes. A form opened as hidden or as an icon returns to the mode specified by its property settings when you show or restore it.
When you open a form with the Window Mode argument set to Dialog, Microsoft Access suspends
the macro until the form is closed or hidden. You can hide a form by setting its Visible
property to No by using the SetValue action.
Tip
You can select a form in the Database window and drag it to a macro action row. This
automatically creates an OpenForm action that opens the form in Form view.
Switching to Design view while the form is open removes most of the argument settings for
the form, such as the Data Mode and Window Mode argument settings. They aren't in effect
even if the user returns to Form view or Datasheet view.
The filter and WHERE condition you apply become the setting of the form's Filter property.
ACTION - OpenQuery action
You can use the OpenQuery action to open a select or crosstab query in Datasheet view,
Design view, or Print Preview. This action runs an action query. You can also select a
data entry mode for the query.
Setting
The OpenQuery action has the following arguments.
Argument Description
Query Name The name of the query to open. The Query Name box in the Action Arguments
section of the Macro window shows all queries in the current database. This
is a required argument. If you run a macro containing the OpenQuery action
in a library database, Microsoft Access looks for the query with this name
first in the library database, then in the current database.
View The view in which the query will open. Click Datasheet, Design, or Print
Preview in the View box. The default is Datasheet.
Data Mode The data entry mode for the query. This applies only to queries opened in
Datasheet view. Click Add (the user can add new records but can't edit
existing records), Edit (the user can edit existing records and add new
records), or Read Only (the user can only view records). The default is
Edit.
Remarks
If you use Datasheet for the View argument, Microsoft Access displays the result set if the
query is a select, crosstab, union, or pass-through query whose ReturnsRecords property is
set to Yes; and it runs the query if it were an action, data-definition, or pass-through query
whose ReturnsRecords property is set to No.
The OpenQuery action is similar to clicking the Open button or Design button in the Database
window after selecting a query in the Queries tab. With this action you can select additional
options.
Tip
You can select a query in the Database window and drag it to a macro action row. This
automatically creates an OpenQuery action that opens the query in Datasheet view.
Switching to Design view while the query is open removes the Data Mode argument setting for
the query. This setting isn't in effect even if the user returns to Datasheet view.
Tip
If you don't want to display the system messages that normally appear when an action query
is run (indicating it's an action query and showing how many records will be affected),
you can use the SetWarnings action to suppress the display of these messages.
To run the OpenQuery action in Visual Basic, use the OpenQuery method of the DoCmd object.
ACTION - OpenReport
You can use the OpenReport action to open a report in Design view or Print Preview,
or to print the report immediately. You can also restrict the records that are printed
in the report.
Setting
The OpenReport action has the following arguments.
Argument Description
Report Name The name of the report to open. The Report Name box in the Action
Arguments section of the Macro window shows all reports in the current
database. This is a required argument.If you run a macro containing the
OpenReport action in a library database, Microsoft Access looks for the
report with this name first in the library database, then in the current
database.
View The view in which the report will open. Click Print (print the report
immediately), Design, or Print Preview in the View box. The default is Print.
Filter Name A filter that restricts the report's records. You can enter the name of
either an existing query or a filter that was saved as a query. However,
the query must include all the fields in the report you are opening or have
its OutputAllFields property set to Yes.
Where Condition A valid SQL WHERE clause (without the word WHERE) or expression that
Microsoft Access uses to select records from the report's underlying table
or query. If you select a filter with the Filter Name argument, Microsoft
Access applies this WHERE clause to the results of the filter. To open a
report and restrict its records to those specified by the value of a control
on a form, use the following expression:
[fieldname] = Forms![formname]![controlname on form]
The fieldname argument is the name of a field in the underlying table or
query of the report you want to open. The controlname on form argument is
the name of the control on the form that contains the value you want records
in the report to match.
Note
The maximum length of the Where condition argument is 256 characters. If you need to enter
a more complex SQL WHERE clause longer than this, use the OpenReport method of the DoCmd
object in Visual Basic instead. You can enter SQL WHERE clause statements of up to 32,768
characters in Visual Basic.
Remarks
The Print setting for the View argument prints the report immediately by using the current
printer settings, without bringing up the Print dialog box. You can also use the OpenReport
action to open and set up a report and then use the PrintOut action to print it. For example,
you may want to modify the report or use the PrintOut action to change the printer settings
before you print.
The filter and WHERE condition you apply become the setting of the report's Filter property.
The OpenReport action is similar to clicking the Design button, the Preview button, or the
Print command on the File menu in the Database window after selecting a report.
Tips
To print similar reports for different sets of data, use a filter or a WHERE clause to
restrict the records printed in the report. Then edit the macro to apply a different filter
or change the Where Condition argument.
You can select a report in the Database window and drag it to a macro action row. This
automatically creates an OpenReport action that opens the report in Print Preview.
ACTION - OpenTable
You can use the OpenTable action to open a table in Datasheet view, Design view, or
Print Preview. You can also select a data entry mode for the table.
Setting
The OpenTable action has the following arguments.
Argument Description
Table Name The name of the table to open. The Table Name box in the Action
Arguments section of the Macro window shows all tables in the current
database. This is a required argument.
If you run a macro containing the OpenTable action in a library database,
Microsoft Access looks for the table with this name first in the library
database, then in the current database.
View The view in which the table will open. Click Datasheet, Design, or Print
Preview in the View box. The default is Datasheet.
Data Mode The data entry mode for the table. This applies only to tables opened in
Datasheet view. Click Add (the user can add new records but can't edit
existing records), Edit (the user can edit existing records and add new
records), or Read Only (the user can only view records). The default is
Edit.
Remarks
This action is similar to clicking the Open button or Design button in the Database window
after selecting a table on the Tables tab.
Tip
You can select a table in the Database window and drag it to a macro action row. This
automatically creates an OpenTable action that opens the table in Datasheet view.
Switching to Design view while the table is open removes the table's Data Mode argument
setting. This setting won't be in effect even if the user returns to Datasheet view.
To run the OpenTable action in Visual Basic, use the OpenTable method of the DoCmd object.
ACTION - RunCode
You can use the RunCode action to call a Visual Basic Function procedure.
Setting
The RunCode action has the following argument.
Action argument Description
Function Name The name of the Visual Basic Function procedure to call. Put any
function arguments in parentheses. Enter the function name in the
Function Name box in the Action Arguments section of the Macro
window. This is a required argument.
Note
To use the Expression Builder to select a function for this argument,
click the Build button to the right of the Function Name box.
Click the desired function in the list in the Expression Builder.
Remarks
The user-defined Function procedures are stored in Microsoft Access modules.
You must include parentheses, even if the Function procedure doesn't have any arguments,
as in the following..
Example
TestFunction()
Unlike user-defined function names used for event property settings, the function name in
the Function Name argument doesn't begin with an equal sign (=).
Microsoft Access ignores the return value of the function.
Tip
To run a Sub procedure or event procedure written in Visual Basic, create a Function
procedure that calls the Sub procedure or event procedure. Then use the RunCode action
to run the Function procedure.
If you use the RunCode action to call a function, Microsoft Access looks for the function
with the name specified by the Function Name argument in the standard modules for the
database. However, when this action runs in response to clicking a menu command on a form
or report or in response to an event on a form or report, Microsoft Access looks for the
function first in the form's or report's class module and then in the standard modules.
Microsoft Access doesn't search the class modules that appear on the Modules tab in the
Database window for the function specified by the Function Name argument.
This action isn't available in Visual Basic. Run the desired Function procedure directly
in Visual Basic.
ACTION - RunSQL
You can use the RunSQL action to run a Microsoft Access action query by using the
corresponding SQL statement. You can also run a data-definition query.
Setting
The RunSQL action has the following arguments.
Action argument Description
SQL Statement The SQL statement for the action query or data-definition query
you want to run. The maximum length of this statement is 256
characters. This is a required argument.
Use Transaction Select Yes to include this query in a transaction. Select No if
you don't want to use a transaction. The default is Yes. Previous
versions of Microsoft Access have always included the query in a
transaction when you ran this action. If you select No for this
argument, the query may run faster.
Remarks
You can use action queries to append, delete, and update records and to save a query's
result set as a new table. You can use data-definition queries to create, alter, and
delete tables, and to create and delete indexes. With the RunSQL action, you can perform
these operations directly from a macro without having to use stored queries.
If you need to type an SQL statement longer than 256 characters, use the RunSQL method
of the DoCmd object in Visual Basic instead. You can type SQL statements of up to
32,768 characters in Visual Basic.
Microsoft Access queries are actually SQL statements that are created when you design
a query by using the design grid in the Query window. The following table shows the
Microsoft Access action queries and data-definition queries and their corresponding SQL
statements.
Query type SQL statement
Action
Append INSERT INTO
Delete DELETE
Make-table SELECT...INTO
Update UPDATE
Data-definition (SQL-specific)
Create a table CREATE TABLE
Alter a table ALTER TABLE
Delete a table DROP TABLE
Create an index CREATE INDEX
Delete an index DROP INDEX
You can also use an IN clause with these statements to modify data in another
database.
Note
To run a select query or crosstab query from a macro, use the View argument of the
OpenQuery action to open an existing select query or crosstab query in Datasheet view.
You can also run existing action queries and SQL-specific queries in the same way.
Tip
To see the SQL equivalent of a Microsoft Access query, click SQL View on the View menu in
the Query window. You can use the listed SQL statements as models to create queries to run
with the RunSQL action. Duplicating an SQL statement in the SQL Statement argument for the
RunSQL action has the same effect as running this Microsoft Access query in the Query window.
ARRAYS, Declaring
Arrays are declared the same way as other variables, using the Dim, Static, Private, or
Public statements. The difference between scalar variables (those that aren't arrays) and
array variables is that you generally must specify the size of the array. An array whose
size is specified is a fixed-size array. An array whose size can be changed while a
program is running is a dynamic array.
Whether an array is indexed from 0 or 1 depends on the setting of the Option Base statement.
If Option Base 1 is not specified, all array indexes begin at zero.
Declaring a Fixed Array
In the following line of code, a fixed-size array is declared as an Integer array having
11 rows and 11 columns:
Dim MyArray(10, 10) As Integer
The first argument represents the rows; the second argument represents the columns.
The default data type of the elements in a declared array is Variant, as with any other
variable declaration. Each numeric Variant element of the array uses 16 bytes. Each string
Variant element uses 22 bytes. To keep code compact, explicitly declare your arrays to
be of non-Variant data type. The following lines of code compare the size of several
arrays:
' Integer array uses 22 bytes (11 elements * 2 bytes).
ReDim MyIntegerArray(10) As Integer
' Double-precision array uses 88 bytes (11 elements * 8 bytes).
ReDim MyDoubleArray(10) As Double
' Variant array uses at least 176 bytes (11 elements * 16 bytes).
ReDim MyVariantArray(10)
' Integer array uses 100 * 100 * 2 bytes (20,000 bytes).
ReDim MyIntegerArray (99, 99) As Integer
' Double-precision array uses 100 * 100 * 8 bytes (80,000 bytes).
ReDim MyDoubleArray (99, 99) As Double
' Variant array uses at least 160,000 bytes (100 * 100 * 16 bytes).
ReDim MyVariantArray(99, 99)
The maximum size of an array varies, based on your operating system and how much memory
is available. Using an array that exceeds the amount of RAM available on your system is
slower because the data must be read from and written to disk.
Declaring a Dynamic Array
By declaring a dynamic array, you can size the array while the code is running. Use a
Static, Dim, Private, or Public statement to declare an array, leaving the parentheses
empty, as shown in the following example.
Dim sngArray() As Single
Note
You can use the ReDim statement to declare an array implicitly within a procedure. Be
careful not to misspell the name of the array when you use the ReDim statement. Even if
the Option Explicit statement is included in the module, a second array will be created.
In a procedure within the array's scope, use the ReDim statement to change the number of
dimensions, to define the number of elements, and to define the upper and lower bounds for
each dimension. You can use the ReDim statement to change the dynamic array as often as
necessary. However, each time you do this, the existing values in the array are lost. Use
ReDim Preserve to preserve the existing values. For example, the following statement
enlarges the array varArray by 10 elements without losing the current values of the original
elements.
ReDim Preserve varArray(UBound(varArray) + 10)
Note
When you use the Preserve keyword with a dynamic array, you can change only the upper bound
of the last dimension, but you can't change the number of dimensions.
ARRAYS, Paramter, Understanding
Understanding Parameter Arrays
A parameter array can be used to pass an array of arguments to a procedure. You don't have
to know the number of elements in the array when you define the procedure.
You use the ParamArray keyword to denote a parameter array. The array must be declared as an
array of type Variant, and it must be the last argument in the procedure definition.
The following example shows how you might define a procedure with a parameter array.
Sub AnyNumberArgs(strName As String, ParamArray intScores() As Variant)
Dim intI As Integer
Debug.Print strName; " Scores"
' Use UBound function to determine upper limit of array.
For intI = 0 To UBound(intScores())
Debug.Print " "; intScores(intI)
Next intI
End Sub
The following examples show how you can call this procedure.
AnyNumberArgs "Jamie", 10, 26, 32, 15, 22, 24, 16
AnyNumberArgs "Kelly", "High", "Low", "Average", "High"
ARRAYS, Using
You can declare an array to work with a set of values of the same data type. An array is
a single variable with many compartments to store values, while a typical variable has only
one storage compartment in which it can store only one value. Refer to the array as a whole
when you want to refer to all the values it holds, or you can refer to its individual
elements.
For example, to store daily expenses for each day of the year, you can declare one array
variable with 365 elements, rather than declaring 365 variables. Each element in an array
contains one value. The following statement declares the array variable curExpense with 365
elements. By default, an array is indexed beginning with zero, so the upper bound of the
array is 364 rather than 365.
Dim curExpense(364) As Currency
To set the value of an individual element, you specify the element's index. The following
example assigns an initial value of 20 to each element in the array.
Sub FillArray()
Dim curExpense(364) As Currency
Dim intI As Integer
For intI = 0 to 364
curExpense(intI) = 20
Next
End Sub
Changing the Lower Bound
You can use the Option Base statement at the top of a module to change the default index
of the first element from 0 to 1. In the following example, the Option Base statement
changes the index for the first element, and the Dim statement declares the array variable
curExpense with 365 elements.
Option Base 1
Dim curExpense(365) As Currency
You can also explicitly set the lower bound of an array by using a To clause, as shown
in the following example.
Dim curExpense(1 To 365) As Currency
Dim strWeekday(7 To 13) As String
Storing Variant Values in Arrays
There are two ways to create arrays of Variant values. One way is to declare an array of
Variant data type, as shown in the following example:
Dim varData(3) As Variant
varData(0) = "Claudia Bendel"
varData(1) = "4242 Maple Blvd"
varData(2) = 38
varData(3) = Format("06-09-1952", "General Date")
The other way is to assign the array returned by the Array function to a Variant variable,
as shown in the following example.
Dim varData As Variant
varData = Array("Ron Bendel", "4242 Maple Blvd", 38, _
Format("06-09-1952", "General Date"))
You identify the elements in an array of Variant values by index, no matter which technique
you use to create the array. For example, the following statement can be added to either of
the preceding examples.
MsgBox "Data for " & varData(0) & " has been recorded."
Using Multidimensional Arrays
In Visual Basic, you can declare arrays with up to 60 dimensions. For example, the
following statement declares a 2-dimensional, 5-by-10 array.
Dim sngMulti(1 To 5, 1 To 10) As Single
If you think of the array as a matrix, the first argument represents the rows and the
second argument represents the columns.
Use nested For...Next statements to process multidimensional arrays. The following
procedure fills a two-dimensional array with Single values.
Sub FillArrayMulti()
Dim intI As Integer, intJ As Integer
Dim sngMulti(1 To 5, 1 To 10) As Single
' Fill array with values.
For intI = 1 To 5
For intJ = 1 To 10
sngMulti(intI, intJ) = intI * intJ
Debug.Print sngMulti(intI, intJ)
Next intJ
Next intI
End Sub
CONSTANTS (Access), Overview
General
Constants improve readability and maintainability of Visual Basic code. Use of
intrinsic constants ensure that code will continue to work if Microsoft changes the numeric
values of the constants.
Access supports three types of constants:
· Symbolic or user-defined constants you create with the Const statement in modules.
· Intrinsic constants, part of Access library or of a referenced library.
· System-defined constants: True, False, and Null.
Symbolic Constants
Using symbolic or user-defined constants with a meaningful name in place of repeated strings,
values or numbers that have no obvious meaning can make the code much easier to read and
maintain.
A constant created by using the Const statement can't be modified or have a new value assigned
to it, and the same name cannot be used when creating another intrinsic constant with the Const
statement.
Examples of declaring constants using the Const statement:
Const conPI = 3.14159265 ' Pi equals this number.
Const conPI2 = conPI * 2 ' A constant used to create another constant.
Const conVersion = "Version 7.0" ' Declare a string constant.
Intrinsic Constants
Access automatically declares intrinsic constants and provides access to VBA constants
and the Data Access Objects (DAO) constants. You can also use constants in other referenced
object libraries. For more information on adding references see Setting References to
Type Libraries.
Any intrinsic constant can be used in a macro or Visual Basic. These constants are available
at all times. The specific built-in constants used with a particular function, method, or
property are described in the Help topic for that function, method, or property.
Note
You can use the Object Browser to view lists of intrinsic constants from all
available object libraries.
Intrinsic constants have a two letter prefix identifying the object library that defines
the constant. Constants from the Microsoft Access library are prefaced with "ac";
constants from the DAO library are prefaced with "db"; and constants from the VBA library
are prefaced with "vb". For example:
· acForm
· dbAppendOnly
· vbCurrency
Note
Because the values represented by the intrinsic constants may change in future Aceess
versions, you should use the constants instead of their actual values. You can, however,
display the actual value of a constant by choosing the constant in the Object Browser
or by typing ?constantname in the Debug window.
You can use intrinsic constants wherever you can use symbolic, or user-defined constants,
including in expressions.
Example
Dim varNum As Variant
If VarType(varNum) = vbCurrency Then
Debug.Print "varNum contains Currency data."
Else
Debug.Print "varNum doesn't contain Currency data."
End If
There are several categories of intrinsic constants. For a list of the intrinsic constants in
a particular category, click the category below:
· The action constants
· The DAO constants
· The event procedure constants
· The Keycode constants
· The miscellaneous constants
· The RunCommand method constants (these are a subset of the action constants)
· The security constants
· The Visual Basic constants
· The VarType function constants
System-Defined Constants
You can use the system-defined constants True, False, and Null anywhere in Microsoft Access.
For example, you can use True in the following macro condition expression. The condition is
met if the Visible property setting for the Employees form equals True.
Forms!Employees.Visible = True
You can use the constant Null anywhere in Microsoft Access. For example, you can use Null to
set the DefaultValue property for a form control by using the following expression:
=Null
CONSTANTS - Action
You can use these constants when you use Visual Basic to run a method of the DoCmd
object. Using these constants with a method of the DoCmd object is the same as running
the corresponding action in a macro. Note that the DoMenuItem method is obsolete; you
should use the RunCommand method and its associated constants in Microsoft Access 97
instead. Constants listed below with an asterisk (*) have been replaced with other
constants, but will still work for the method or methods listed.
DoCmd object constants Used with
acActiveDataObject GoToRecord
acAdd OpenQuery, OpenTable
acAll FindRecord
acAnywhere FindRecord
acCopy DoMenuItem
acCurrent FindRecord
acCut DoMenuItem
acDataForm GoToRecord
acDataQuery GoToRecord
acDataTable GoToRecord
acDefault Close, CopyObject, DeleteObject,
Rename, RepaintObject, Save
acDelete DoMenuItem
acDesign OpenForm
acDialog OpenForm
acDown FindRecord
acDraft PrintOut
acEdit OpenQuery, OpenTable
acEditMenu DoMenuItem
acEntire FindRecord
acExit* Quit (DoCmd object), Quit (Application object)
acExport TransferDatabase, TransferSpreadsheet
acExportDelim TransferText
acExportFixed TransferText
acExportHTML TransferText
acExportMerge TransferText
acFile DoMenuItem
acFirst GoToRecord
acForm Close, CopyObject, DeleteObject, Rename,
RepaintObject, Save, SelectObject, TransferDatabase
acFormAdd OpenForm
acFormatActiveXServer OutputTo
acFormatHTML OutputTo, SendObject
acFormatIIS OutputTo
acFormatRTF OutputTo, SendObject
acFormatTXT OutputTo, SendObject
acFormatXLS OutputTo, SendObject
acFormBar DoMenuItem
acFormDS OpenForm
acFormEdit OpenForm
acFormPropertySettings OpenForm
acFormReadOnly OpenForm
acGoTo GoToRecord
acHidden OpenForm
acHigh PrintOut
acIcon OpenForm
acImport TransferDatabase, TransferSpreadsheet
acImportDelim TransferText
acImportFixed TransferText
acImportHTML TransferText
acLast GoToRecord
acLink TransferDatabase, TransferSpreadsheet
acLinkDelim TransferText
acLinkFixed TransferText
acLinkHTML TransferText
acLow PrintOut
acMacro Close, CopyObject, DeleteObject, Rename,
RepaintObject, Save, SelectObject, TransferDatabase
acMedium PrintOut
acMenuCheck SetMenuItem
acMenuGray SetMenuItem
acMenuUncheck SetMenuItem
acMenuUngray SetMenuItem
acMenuVer1X DoMenuItem
acMenuVer20 DoMenuItem
acMenuVer70 DoMenuItem
acModule Close, CopyObject, DeleteObject, Rename,
RepaintObject, Save, SelectObject, TransferDatabase
acNew DoMenuItem
acNewRec GoToRecord
acNext GoToRecord
acNormal OpenForm
acObject DoMenuItem
acObjectUpdate DoMenuItem
acObjectVerb DoMenuItem
acOutputForm OutputTo
acOutputModule OutputTo
acOutputQuery OutputTo
acOutputReport OutputTo
acOutputTable OutputTo
acPages PrintOut
acPaste DoMenuItem
acPreview OpenForm
acPrevious GoToRecord
acPrintAll PrintOut
acPrompt* Close, Quit (DoCmd object), Quit (Application object)
acQuery Close, CopyObject, DeleteObject, Rename,
RepaintObject, Save, SelectObject, TransferDatabase
acQuitPrompt Quit (DoCmd object), Quit (Application object)
acQuitSaveAll Quit (DoCmd object), Quit (Application object)
acQuitSaveNone Quit (DoCmd object), Quit (Application object)
acReadOnly OpenQuery, OpenTable
acRecordsMenu DoMenuItem
acRefresh DoMenuItem
acReport Close, CopyObject, DeleteObject, Rename,
RepaintObject, Save, SelectObject, TransferDatabase
acSaveForm DoMenuItem
acSaveFormAs DoMenuItem
acSave* Quit (DoCmd object), Quit (Application object)
acSaveNo Close
acSavePrompt Close
acSaveRecord DoMenuItem
acSaveYes Close
acSearchAll FindRecord
acSelectAllRecords DoMenuItem
acSelection PrintOut
acSelectRecord DoMenuItem
acSendForm SendObject
acSendModule SendObject
acSendNoObject SendObject
acSendQuery SendObject
acSendReport SendObject
acSendTable SendObject
acSpreadsheetTypeExcel3 TransferSpreadsheet
acSpreadsheetTypeExcel4 TransferSpreadsheet
acSpreadsheetTypeExcel5 TransferSpreadsheet
acSpreadsheetTypeExcel7 TransferSpreadsheet
acSpreadsheetTypeExcel97 TransferSpreadsheet
acSpreadsheetTypeLotusWK1 TransferSpreadsheet
acSpreadsheetTypeLotusWK3 TransferSpreadsheet
acSpreadsheetTypeLotusWK4 TransferSpreadsheet
acSpreadsheetTypeLotusWJ2--- Japanese version only TransferSpreadsheet
acStart FindRecord
acTable Close, CopyObject, DeleteObject, Rename,
RepaintObject, Save, SelectObject, TransferDatabase
acToolbarNo ShowToolbar
acToolbarWhereApprop ShowToolbar
acToolbarYes ShowToolbar
acUndo DoMenuItem
acUp FindRecord
acViewDesign OpenQuery, OpenReport, OpenTable
acViewNormal OpenQuery, OpenReport, OpenTable
acViewPreview OpenQuery, OpenReport, OpenTable
acWindowNormal OpenForm
CONSTANTS - DAO (Data Access Objects)
constants all begin with the letters db and are documented with the method or property
to which they apply.
Legend: R=Read-only, RW=Read/Write
AllPermissions Property Constants (All Are R)
For any Container or Document object:
Constant Allows user to
dbSecReadDef read the table definition, including column and index information.
dbSecWriteDef modify or delete the table definition, including column and index
information.
dbSecRetrieveData retrieve data from the Document object.
dbSecInsertData add records.
dbSecReplaceData modify records.
dbSecDeleteData delete records.
Documents collection: Databases container or Document object may include"action:
Constant Allows user to
dbSecDeleteData delete records.
dbSecDBAdmin replicate the database and change the database password.
dbSecDBCreate create new databases. This setting is valid only on the Databases
container in the workgroup information file (System.mdw).
dbSecDBExclusive exclusive access to the database.
dbSecDBOpen open the database.
Attributes Property Constants
A Field object's Attributes property may include:
Constant Description
dbFixedField RW) Fixed field size (default for Numeric fields)
dbVariableField RW) Variable field size (Text fields only)
dbAutoIncrField RW) New record field value incremented to unique Long integer
(in a Microsoft Jet workspace, available only on TableDef objects
opened from .mdb files)
dbUpdatableField R) Field is updatable
dbDescending RW) Field sorted in descending order (Microsoft Jet workspaces only)
dbHyperlinkField RW) The field contains hyperlink information (Memo fields in Microsoft Jet workspaces only)
dbSystemField R) The field is a replication field (on a TableDef object in
Microsoft Jet databases only)
A Relation object's Attributes property may include:
Constant Description
dbRelationUnique RW) One-to-one relationship
dbRelationDontEnforce RW) Relationship not enforced (no referential integrity)
dbRelationInherited R) Relationship exists in the database containing the two linked tables
dbRelationUpdateCascade RW) Updates cascade
dbRelationDeleteCascade RW) Deletions cascade
A TableDef object's Attributes property may include:
Constant Description
dbAttachExclusive RW) Opens a linked Microsoft Jet database engine table for exclusive use.
dbAttachSavePWD RW) Saves user ID and password for linked remote table.
dbSystemObject R) System table
dbHiddenObject RW) Hidden table (for temporary use)
dbAttachedTable R) Linked non-ODBC database table
dbAttachedODBC R) Linked ODBC database table
CollatingOrder Property Constants (All Are RW)
Constant Description
dbSortGeneral English, German, French, and Portuguese collating order
dbSortUndefined Collating order undefined or unknown
DefaultCursorDriver Property (All are RW)
Constant Description
dbUseDefaultCursor (Default) Uses server-side cursors if the server supports them;
otherwise uses the ODBC Cursor Library.
dbUseODBCCursor Always uses the ODBC Cursor Library. This option provides better
performance for small result sets, but degrades quickly for larger
result sets.
dbUseServerCursor Always uses server-side cursors. For most large operations this
option provides better performance, but might cause more network
traffic.
dbUseClientBatchCursor Always uses the FoxPro Cursor Library. This option is required
for performing batch updates.
dbUseNoCursor Opens all cursors (that is, Recordset objects) as forward-only type,
read-only, with a rowset size of 1. Also known as "cursorless queries."
Direction Property Constants (All Are RW)
Constant Description
dbParamInput (Default) Passes information to the procedure.
dbParamInputOutput Passes information both to and from the procedure.
dbParamOutput Returns information from the procedure as in an output parameter in SQL.
dbParamReturnValue Passes the return value from a procedure.
EditMode Property Constants (All Are R)
Constant Description
dbEditNone No editing operation in effect.
dbEditInProgress Edit method invoked.
dbEditAdd AddNew method invoked.
Permissions Property Constants (All are RW)
A Container object's Permissions property may include:
Constant Allows user
dbSecNoAccess NO-Denies user access to the object.
dbSecFullAccess full access to the object.
dbSecDelete to delete the object.
dbSecReadSec to read the object's security-related information.
dbSecWriteSec to alter access permissions.
dbSecWriteOwner to change the Owner property setting.
A database Container's Permissions property may include (All are RW):
Constant Allows user
dbSecDBAdmin permission to make a database replicable and change the database password.
dbSecDBCreate to create new databases (valid only on the databases Container
object in the system database).
dbSecDBOpen to open the database.
dbSecDBExclusive exclusive access.
A tables Container's Permissions property may include(All are RW):
Constant Allows user to
dbSecCreate create new tables (valid only with a Container object that
represents a table or with the databases Container object in the
system database).
dbSecReadDef read the table definition, including column and index information.
dbSecWriteDef modify or delete the table definition, including column and index
information.
dbSecRetrieveData retrieve data from the document.
dbSecInsertData add records.
dbSecReplaceData modify records.
dbSecDeleteData delete records.
A Document object's Permissions property may include (All are RW):
Constant Allows user to
dbSecCreate create new tables (valid only with a Container object that represents
a table).
dbSecDBCreate create new databases (valid only on the databases Container object
in the system database).
dbSecDBOpen open the database.
dbSecDBExclusive exclusive access.
dbSecDelete delete the object.
dbSecDeleteData delete records.
dbSecFullAccess full access to the object.
dbSecInsertData add records.
dbSecReadDef read the table definition, including column and index information.
dbSecReadSec read the object's security-related information.
dbSecReplaceData modify records.
dbSecRetrieveData retrieve data from the document.
dbSecWriteDef modify or delete the table definition, including column and index information.
dbSecWriteSec alter access permissions.
dbSecWriteOwner change the Owner property setting.
Prepare Property Constants (All Are RW)
Constant Description
dbQPrepare (Default) The statement is prepared (that is, the ODBC SQLPrepare API
is called).
dbQUnprepare The statement is not prepared (that is, the ODBC SQLExecDirect API is called).
RecordStatus Property Constants (All Are R)
Constant Description
dbDBDeleted The record has been deleted locally and in the database.
dbDeleted The record has been deleted, but not yet deleted in the database.
dbRecordModified The record has been modified and not updated in the database.
dbRecordNew The record has been inserted with the AddNew method, but not yet
inserted into the database.
dbRecordUnmodified (Default) The record has not been modified or has been updated
successfully.
Type Property Constants
A Field, Parameter, or Property object's Type property may include (All are RW):
Constant Description
dbBigInt Big Integer data (ODBCDirect only)
dbBinary Binary data
dbBoolean Boolean (True/False) data
dbByte Byte (8-bit) data
dbChar Character data (ODBCDirect only)
dbCurrency Currency data
dbDate Date value data
dbDecimal Decimal data (ODBCDirect only)
dbDouble Double-precision floating-point data
dbFloat Floating-point data (ODBCDirect only)
dbGUID GUID data
dbInteger Integer data
dbLong Long Integer data
dbLongBinary Binary data (bitmap)
dbMemo Memo data (extended text)
dbNumeric Numeric data (ODBCDirect only)
dbSingle Single-precision floating-point data
dbText Text data (variable width)
dbTime Data in time format (ODBCDirect only)
dbTimeStamp Data in time and date format (ODBCDirect only)
dbVarBinary Variable Binary data (ODBCDirect only)
For any QueryDef object, the Type property may include any of the following (All are R):
Constant Description
dbQAction Action query
dbQAppend Append query
dbQCompound Compound query (ODBCDirect workspaces only)
dbQCrosstab Crosstab query
dbQDDL Data-definition language (DDL) query
dbQDelete Delete query
dbQMakeTable Make-table query
dbQProcedure SQL procedure that executes a stored procedure (ODBCDirect workspaces only)
dbQSelect Select query
dbQSetOperation Set operation query
dbQSPTBulk Bulk operation query
dbQSQLPassThrough SQL pass-through query
dbQUpdate Update query
A Recordset object's Type property may include (All are R):
Constants Opens a
dbOpenDynamic dynaset-type Recordset (ODBCDirect workspaces only)
dbOpenDynaset dynaset-type Recordset
dbOpenForwardOnly forward-only type Recordset
dbOpenSnapshot snapshot-type Recordset
dbOpenTable table-type Recordset (Microsoft Jet workspaces only)
UpdateOptions Property Constants (All Are RW)
Constant Description
dbCriteriaKey (Default) Uses just the key column(s) in the where clause.
dbCriteriaModValues Uses the key column(s) and all updated columns in the where clause.
dbCriteriaAllCols Uses the key column(s) and all the columns in the where clause.
dbCriteriaTimeStamp Uses just the timestamp column if available (will generate a
run-time error if no timestamp column is in the result set).
dbCriteriaDeleteInsert Uses a pair of DELETE and INSERT statements for each modified row.
dbCriteriaUpdate (Default) Uses an UPDATE statement for each modified row.
CompactDatabase, CreateDatabase Methods Locale Argument Constants (All Are RW)
Constant Description
dbLangGeneral English, German, French, Portuguese, Italian, and Modern Spanish
CompactDatabase Method Options Argument Constants (All Are RW)
Constant Description
dbDecrypt Decrypts database while compacting
dbEncrypt Encrypts database
dbVersion10 Microsoft Jet database engine version 1.0
dbVersion11 Microsoft Jet database engine version 1.1
dbVersion20 Microsoft Jet database engine version 2.0
dbVersion30 Microsoft Jet database engine version 3.0
CreateDatabase Method Options Argument Constants (All Are RW)
Constant Description
dbEncrypt Encrypts database
dbVersion10 Microsoft Jet database engine version 1.0
dbVersion11 Microsoft Jet database engine version 1.1
dbVersion20 Microsoft Jet database engine version 2.0
dbVersion30 Microsoft Jet database engine version 3.0
CreateWorkspace Method Type Argument Constants
A Workspace object's Type property and DBEngine object's DefaultType property use any
of the following: (All Are RW)
Constant Description
dbUseODBC The next workspace created will use ODBCDirect.
dbUseJet The next workspace created will use the Microsoft Jet database engine.
Execute Method Options Argument Constants (All Are RW)
Constant Description
dbDenyWrite Denies write permission to other users (Microsoft Jet workspaces only).
dbInconsistent Allows inconsistent updates (Microsoft Jet workspaces only).
dbConsistent Allows consistent updates (Microsoft Jet workspaces only).
dbSQLPassThrough An SQL pass-through. Causes the SQL statement to be passed to an ODBC
database for processing (Microsoft Jet workspaces only).
dbFailOnError Rolls back updates if an error occurs (Microsoft Jet workspaces only).
dbSeeChanges Generates a run-time error if another user is changing data you are
editing (Microsoft Jet workspaces only).
dbRunAsync Executes the query asynchronously (ODBCDirect workspaces only).
dbExecDirect Executes the query without first calling the SQLPrepare ODBC function
(ODBCDirect workspaces only).
Idle Method Optional Argument Constant (This Is RW)
Constant Description
dbRefreshCache Forces any pending writes to disk, and refreshes memory from current
disk files.
MakeReplica Method Optional Argument Constants (All are RW)
Constant Description
dbRepMakePartial Creates a partial replica.
dbRepMakeReadOnly Makes replicable elements of new database read-only.
OpenConnection and OpenDatabase Methods Option Argument Constants (All Are RW)
Constant Description
dbDriverNoPrompt The driver manager uses the connection string provided
in connect. If sufficient information is not provided, a
trappable error is returned.
dbDriverPrompt The driver manager displays the ODBC Data Sources dialog
box. The connection string used to establish the connection
is constructed from the data source name (DSN) selected
and completed by the user via the dialog boxes.
dbDriverComplete If the connection string provided includes the DSN keyword,
the driver manager uses the string as provided in connect,
otherwise it behaves as it does when dbDriverPrompt is
specified.
dbDriverCompleteRequired (Default) Behaves like dbDriverComplete except the driver
disables the controls for any information not required to
complete the connection.
OpenRecordset Method Type Argument Constants (All Are RW)
Constant Description
dbOpenDynamic Opens a dynamic-type Recordset (ODBCDirect workspaces only)
dbOpenDynaset Opens a dynaset-type Recordset
dbOpenForwardOnly Opens a forward-only type Recordset
dbOpenSnapshot Opens a snapshot-type Recordset
dbOpenTable Opens a table-type Recordset (Microsoft Jet workspaces only)
OpenRecordset Method LockEdits Argument Constants (All Are RW)
Constant Description
dbPessimistic Pessimistic concurrency. Cursor uses the lowest level of locking
sufficient to ensure the record can be updated.
dbReadOnly Cursor is read-only. No updates are allowed.
dbOptimistic Optimistic concurrency based on record ID. Cursor compares record
ID in old and new records to determine if changes have been made
since the record was last accessed.
dbOptimisticValue Optimistic concurrency based on record values. Cursor compares
data values in old and new records to determine if changes have been
made since the record was last accessed (ODBCDirect workspaces only).
dbOptimisticBatch Enables batch optimistic updates (ODBCDirect workspaces only).
OpenRecordset Method Options Argument Constants (All Are RW)
Constant Description
dbDenyWrite Prevents other users from changing Recordset records (Microsoft Jet
workspaces only).
dbDenyRead Prevents other users from reading Recordset records (table-type in
Microsoft Jet workspaces only).
dbReadOnly Opens the Recordset as read-only (Microsoft Jet workspaces only).
dbAppendOnly Allows user to add new records to the dynaset, but prevents user
from reading existing records (dynaset-type in Microsoft Jet
workspaces only).
dbInconsistent Applies updates to all dynaset fields, even if other records are
affected (dynaset- and snapshot-type in Microsoft Jet workspaces
only).
dbConsistent Applies updates only to those fields that will not affect other
records in the dynaset (dynaset- and snapshot-type in Microsoft Jet
workspaces only).
dbSQLPassThrough Sends an SQL statement to an ODBC database (snapshot-type in
Microsoft Jet workspaces only).
dbForwardOnly Creates a forward-only scrolling snapshot-type Recordset
(snapshot-type in Microsoft Jet workspaces only).
dbSeeChanges Generates a run-time error if another user is changing data you
are editing (dynaset-type in Microsoft Jet workspaces only).
dbRunAsync Executes the query asynchronously (ODBCDirect workspaces only).
dbExecDirect Executes the query without first calling the SQLPrepare ODBC function
(ODBCDirect workspaces only).
SetOption Method Parameter Constants (All Are RW)
Constant The Key
dbPageTimeout PageTimeout
dbSharedAsyncDelay SharedAsyncDelay
dbExclusiveAsyncDelay ExclusiveAsyncDelay
dbLockRetry LockRetry
dbUserCommitSync UserCommitSync
dbImplicitCommitSync ImplicitCommitSync
dbMaxBufferSize MaxBufferSize
dbMaxLocksPerFile MaxLocksPerFile
dbLockDelay LockDelay
dbRecycleLVs RecycleLVs
dbFlushTransactionTimeout FlushTransactionTimeout
Synchronize Method Exchange Argument Constants (All Are RW)
Constant Description
dbRepExportChanges Sends changes from current database to target database.
dbRepImportChanges Receives changes from target database.
dbRepImpExpChanges Sends and receives data in a bidirectional exchange.
dbRepSyncInternet Exchanges data between files connected via an Internet pathway.
Update Method Type Argument Constants (All Are RW)
Constant Description
dbUpdateRegular (Default) Pending changes aren't cached and are written to disk immediately.
dbUpdateBatch All pending changes in the update cache are written to disk.
dbUpdateCurrentRecord Only the current record's pending changes are written to disk.
CancelUpdate Method Type Argument Constants (All Are RW)
Constant Description
dbUpdateRegular (Default) Pending changes aren't cached and are written to disk immediately.
dbUpdateBatch All pending changes in the update cache are written to disk.
CONSTANTS - Enumerated (Access 97)
In Access 97 a number of intrinsic constants were added or changed to create lists of
"enumerated" constants that are displayed in the Module window -> Auto List Members
list for the arguments of various Microsoft Access methods, functions, and properties,
or as the setting of various Microsoft Access properties. You can select the appropriate
constant from the list in the Module window, instead of having to remember the constant
or look it up in the Help topic.
The following information applies to enumerated constants:
The set of enumerated constants for each method, function, or property argument (For
property settings, the name isn't displayed, just the list of constants.) has a name,
which is displayed in the syntax line for the method, function, or property in
the Module window when the Auto Quick Info option is checked, (Navigate:
Tool menu -> Options (dialog) -> Module tab).
For example, the syntax line for the OpenForm method of the DoCmd object shows [View as
AcFormView = acNormal] for the view argument of this method. AcFormView is the name of
this set of enumerated constants, and acNormal is the default setting for the argument.
The Object Browser also lists the names of the sets of enumerated constants in the Classes
box and lists the intrinsic constants contained in each of these sets in the Members box.
·For constant names that have changed, the old constants will still work. For example,
one of the intrinsic constants for the save argument of the Close method of the DoCmd object
was acPrompt. It's now acSavePrompt, but acPrompt will still work.
·In a number of cases in previous versions of Microsoft Access, you could leave an
argument setting blank, and Microsoft Access would perform the default action for that
argument. For example, you could leave the objecttype (and objectname) arguments of the
Close method blank, and Microsoft Access would close the active window. For the new sets of
enumerated constants, the blank setting has been replaced with a new default constant. For
example, the objecttype argument of the Close method now has a new default constant,
acDefault. Setting this argument to the new constant has the same effect as leaving the
argument blank. In addition, you can still leave such arguments blank, and Microsoft
Access will assume the new default constant.
·There's one exception to this. If you run Visual Basic code from previous versions of
Visual Basic in Microsoft Access by using Automation, blank arguments will cause an error
for those arguments that have the new default constants. This problem doesn't occur for
old Visual Basic for Applications or Visual Basic code run directly in Microsoft Access.
The following table lists all the intrinsic constants that have been added or changed in
order to create enumerated constant lists in Microsoft Access 97.
Language element Argument Old constant New constant
Close method save acPrompt acSavePrompt
Close method objecttype (none) acDefault
CopyObject method sourceobjecttype (none) acDefault
DeleteObject method objecttype (none) acDefault
GoToRecord method objecttype acTable acDataTable
GoToRecord method objecttype acQuery acDataQuery
GoToRecord method objecttype acForm acDataForm
GoToRecord method objecttype (none) acActiveDataObject
OpenForm method datamode acAdd acFormAdd
OpenForm method datamode acEdit acFormEdit
OpenForm method datamode acReadOnly acFormReadOnly
OpenForm method datamode (none) acFormPropertySettings
OpenForm method windowmode acNormal acWindowNormal
OpenQuery method view acNormal acViewNormal
OpenQuery method view acDesign acViewDesign
OpenQuery method view acPreview acViewPreview
OpenReport method view acNormal acViewNormal
OpenReport method view acDesign acViewDesign
OpenReport method view acPreview acViewPreview
OpenTable method view acNormal acViewNormal
OpenTable method view acDesign acViewDesign
OpenTable method view acPreview acViewPreview
OutputTo method objecttype acTable acOutputTable
OutputTo method objecttype acQuery acOutputQuery
OutputTo method objecttype acForm acOutputForm
OutputTo method objecttype acReport acOutputReport
OutputTo method objecttype acModule acOutputModule
Quit method (DoCmd options acPrompt acQuitPrompt
object)
Quit method (DoCmd options acSaveYes or acQuitSaveAll
object) acSave
Quit method (DoCmd options acSaveNo or acQuitSaveNone
object) acExit
Quit method options acPrompt acQuitPrompt
(Application object)
Quit method options acSaveYes or acQuitSaveAll
(Application object) acSave
Quit method options acExit acQuitSaveNone
(Application object)
Rename method objecttype (none) acDefault
RepaintObject method objecttype (none) acDefault
Save method objecttype (none) acDefault
SendObject method objecttype acTable acSendTable
SendObject method objecttype acQuery acSendQuery
SendObject method objecttype acForm acSendForm
SendObject method objecttype acReport acSendReport
SendObject method objecttype acModule acSendModule
SendObject method objecttype (none) acSendNoObject
TransferSpreadsheet spreadsheettype (none) acSpreadsheetTypeExcel3
method
TransferSpreadsheet spreadsheettype (none) acSpreadsheetTypeExcel4
method
TransferSpreadsheet spreadsheettype (none) acSpreadsheetTypeExcel5
method
TransferSpreadsheet spreadsheettype (none) acSpreadsheetTypeExcel7
method
TransferSpreadsheet spreadsheettype (none) acSpreadsheetTypeExcel97
method
TransferSpreadsheet spreadsheettype (none) acSpreadsheetTypeLotusWK1
method
TransferSpreadsheet spreadsheettype (none) acSpreadsheetTypeLotusWK3
method
TransferSpreadsheet spreadsheettype (none) acSpreadsheetTypeLotusWJ2
method — Japanese version only
TransferSpreadsheet spreadsheettype (none) acSpreadsheetTypeLotusWK4
method
TransferText method transfertype (none) acImportHTML
TransferText method transfertype (none) acExportHTML
TransferText method transfertype (none) acLinkHTML
HyperlinkPart function part (none) acAddress
HyperlinkPart function part (none) acDisplayedValue
HyperlinkPart function part (none) acDisplayName
HyperlinkPart function part (none) acSubAddress
Type property [setting] (none) acClassModule
Type property [setting] (none) acStandardModule
CONSTANTS - RunCommand
You can use these constants in Visual Basic when you use the RunCommand method. Using these
constants with the RunCommand method is the same as supplying the value for the RunCommand
action in a macro.
acCmdAboutMicrosoftAccess acCmdHideColumns acCmdRefreshPage
acCmdAddWatch acCmdHideTable acCmdRegisterActiveXControls
acCmdAdvancedFilterSort acCmdHorizontalSpacingDecrease acCmdRelationships
acCmdAlignBottom acCmdHorizontalSpacingIncrease acCmdRemoveFilterSort
acCmdAlignLeft acCmdHorizontalSpacingMakeEqual acCmdRemoveTable
acCmdAlignRight acCmdHyperlinkDisplayText acCmdRename
acCmdAlignToGrid acCmdImport acCmdRenameColumn
acCmdAlignTop acCmdIndent acCmdRepairDatabase
acCmdAlignToShortest acCmdIndexes acCmdReplace
acCmdAlignToTallest acCmdInsertActiveXControl acCmdReportHdrFtr
acCmdAnalyzePerformance acCmdInsertChart acCmdReset
acCmdAnalyzeTable acCmdInsertFile acCmdResolveConflicts
acCmdAnswerWizard acCmdInsertFileIntoModule acCmdRowHeight
acCmdApplyDefault acCmdInsertHyperlink acCmdRun
acCmdApplyFilterSort acCmdInsertLookupColumn acCmdRunMacro
acCmdAppMaximize acCmdInsertLookupField acCmdRunOpenMacro
acCmdAppMinimize acCmdInsertObject acCmdSave
acCmdAppMove acCmdInsertPage acCmdSaveAllModules
acCmdAppRestore acCmdInsertPicture acCmdSaveAs
acCmdAppSize acCmdInsertProcedure acCmdSaveAsASP
acCmdArrangeIconsAuto acCmdInsertQueryColumn acCmdSaveAsHTML
acCmdArrangeIconsByCreated acCmdInsertRows acCmdSaveAsIDC
acCmdArrangeIconsByModified acCmdInsertTableColumn acCmdSaveAsQuery
acCmdArrangeIconsByName acCmdInvokeBuilder acCmdSaveAsReport
acCmdArrangeIconsByType acCmdJoinProperties acCmdSaveLayout
acCmdAutoCorrect acCmdLastPosition acCmdSaveModuleAsText
acCmdAutoDial acCmdLayoutPreview acCmdSaveRecord
acCmdAutoFormat acCmdLineUpIcons acCmdSelectAll
acCmdBookmarksClearAll acCmdLinkTables acCmdSelectAllRecords
acCmdBookmarksNext acCmdListConstants acCmdSelectForm
acCmdBookmarksPrevious acCmdLoadFromQuery acCmdSelectRecord
acCmdBookmarksToggle acCmdMacroConditions acCmdSelectReport
acCmdBringToFront acCmdMacroNames acCmdSend
acCmdCallStack acCmdMakeMDEFile acCmdSendToBack
acCmdChangeToCheckBox acCmdMicrosoftAccessHelpTopics acCmdSetControlDefaults
acCmdChangeToComboBox acCmdMicrosoftOnTheWeb acCmdSetDatabasePassword
acCmdChangeToImage acCmdMinimize acCmdSetNextStatement
acCmdChangeToLabel acCmdMoreWindows acCmdShowAllRelationships
acCmdChangeToListBox acCmdNewDatabase acCmdShowDirectRelationships
acCmdChangeToOptionButton acCmdNewObjectAutoForm acCmdShowMembers
acCmdChangeToTextBox acCmdNewObjectAutoReport acCmdShowNextStatement
acCmdChangeToToggleButton acCmdNewObjectClassModule acCmdShowOnlyWebToolbar
acCmdClearAll acCmdNewObjectForm acCmdShowTable
acCmdClearAllBreakpoints acCmdNewObjectMacro acCmdSingleStep
acCmdClearGrid acCmdNewObjectModule acCmdSizeToFit
acCmdClearItemDefaults acCmdNewObjectQuery acCmdSizeToFitForm
acCmdClose acCmdNewObjectReport acCmdSizeToGrid
acCmdCloseWindow acCmdNewObjectTable acCmdSizeToNarrowest
acCmdColumnWidth acCmdObjBrwFindWholeWordOnly acCmdSizeToWidest
acCmdCompactDatabase acCmdObjBrwGroupMembers acCmdSnapToGrid
acCmdCompileAllModules acCmdObjBrwHelp acCmdSortAscending
acCmdCompileAndSaveAllModules acCmdObjBrwShowHiddenMembers acCmdSortDescending
acCmdCompileLoadedModules acCmdObjBrwViewDefinition acCmdSortingAndGrouping
acCmdCompleteWord acCmdObjectBrowser acCmdSpelling
acCmdControlWizardsToggle acCmdOLEDDELinks acCmdSQLView
acCmdConvertDatabase acCmdOLEObjectConvert acCmdStartupProperties
acCmdConvertMacrosToVisualBasic acCmdOLEObjectDefaultVerb acCmdStepOut
acCmdCopy acCmdOpenDatabase acCmdStepOver
acCmdCopyHyperlink acCmdOpenHyperlink acCmdStepToCursor
acCmdCreateMenuFromMacro acCmdOpenNewHyperlink acCmdStopLoadingPage
acCmdCreateRelationship acCmdOpenSearchPage acCmdSubformDatasheet
acCmdCreateReplica acCmdOpenStartPage acCmdSynchronizeNow
acCmdCreateShortcut acCmdOpenTable acCmdTabControlPageOrder
acCmdCreateShortcutMenuFromMacr acCmdOpenURL acCmdTableNames
acCmdCreateToolbarFromMacro acCmdOptions acCmdTabOrder
acCmdCut acCmdOutdent acCmdTestValidationRules
acCmdDatabaseProperties acCmdOutputToExcel acCmdTileHorizontally
acCmdDataEntry acCmdOutputToRTF acCmdTileVertically
acCmdDatasheetView acCmdOutputToText acCmdToggleBreakpoint
acCmdDateAndTime acCmdPageHdrFtr acCmdToggleFilter
acCmdDebugWindow acCmdPageNumber acCmdToolbarControlProperties
acCmdDelete acCmdPageSetup acCmdToolbarsCustomize
acCmdDeletePage acCmdParameterInfo acCmdTransparentBackground
acCmdDeleteQueryColumn acCmdPaste acCmdTransparentBorder
acCmdDeleteRecord acCmdPasteAppend acCmdUndo
acCmdDeleteRows acCmdPasteSpecial acCmdUnfreezeAllColumns
acCmdDeleteTab acCmdPreviewEightPages acCmdUnhideColumns
acCmdDeleteTableColumn acCmdPreviewFourPages acCmdUserAndGroupAccounts
acCmdDeleteWatch acCmdPreviewOnePage acCmdUserAndGroupPermissions
acCmdDesignView acCmdPreviewTwelvePages acCmdUserLevelSecurityWizard
acCmdDocMaximize acCmdPreviewTwoPages acCmdVerticalSpacingDecrease
acCmdDocMove acCmdPrimaryKey acCmdVerticalSpacingIncrease
acCmdDocRestore acCmdPrint acCmdVerticalSpacingMakeEqual
acCmdDocSize acCmdPrintPreview acCmdViewCode
acCmdDocumenter acCmdProcedureDefinition acCmdViewDetails
acCmdDuplicate acCmdProperties acCmdViewForms
acCmdEditHyperlink acCmdPublish acCmdViewGrid
acCmdEditingAllowed acCmdPublishDefaults acCmdViewLargeIcons
acCmdEditRelationship acCmdQueryParameters acCmdViewList
acCmdEditWatch acCmdQueryTotals acCmdViewMacros
acCmdEncryptDecryptDatabase acCmdQueryTypeAppend acCmdViewModules
acCmdEnd acCmdQueryTypeCrosstab acCmdViewQueries
acCmdExit acCmdQueryTypeDelete acCmdViewReports
acCmdFavoritesAddTo acCmdQueryTypeMakeTable acCmdViewRuler
acCmdFavoritesOpen acCmdQueryTypeSelect acCmdViewSmallIcons
acCmdFieldList acCmdQueryTypeSQLDataDefinition acCmdViewTables
acCmdFilterByForm acCmdQueryTypeSQLPassThrough acCmdViewToolbox
acCmdFilterBySelection acCmdQueryTypeSQLUnion acCmdWindowArrangeIcons
acCmdFilterExcludingSelection acCmdQueryTypeUpdate acCmdWindowCascade
acCmdFind acCmdQuickInfo acCmdWindowHide
acCmdFindNextWordUnderCursor acCmdQuickPrint acCmdWindowSplit
acCmdFindPrevious acCmdQuickWatch acCmdWindowUnhide
acCmdFindPrevWordUnderCursor acCmdRecordsGoToFirst acCmdWordMailMerge
acCmdFitToWindow acCmdRecordsGoToLast acCmdZoom10
acCmdFont acCmdRecordsGoToNew acCmdZoom25
acCmdFormatCells acCmdRecordsGoToNext acCmdZoom50
acCmdFormHdrFtr acCmdRecordsGoToPrevious acCmdZoom75
acCmdFormView acCmdRecoverDesignMaster acCmdZoom100
acCmdFreezeColumn acCmdRedo acCmdZoom150
acCmdGoBack acCmdReferences acCmdZoom200
acCmdGoContinue acCmdRefresh acCmdZoomBox
acCmdGoForward
CONSTANTS - Variable Type (Visual Basic VarType Constants)
Constant Value Description
vbEmpty 0 Uninitialized (default)
vbNull 1 Contains no valid data
vbInteger 2 Integer
vbLong 3 Long integer
vbSingle 4 Single-precision floating-point number
vbDouble 5 Double-precision floating-point number
vbCurrency 6 Currency
vbDate 7 Date
vbString 8 String
vbObject 9 Object
vbError 10 Error
vbBoolean 11 Boolean
vbVariant 12 Variant (used only for arrays of variants)
vbDataObject 13 Data access object
vbDecimal 14 Decimal
vbByte 17 Byte
vbArray 8192 Array
CONTROLS - Combo Box
(also see
Properties)
The combo box control combines the features of a text box and a list box. Use a combo box
when you want the option of either typing a value or selecting a value from a predefined list.
Remarks
In Form view, Microsoft Access doesn't display the list until you click the combo box's
arrow.
If you have Control Wizards on before you select the combo box tool, you can create a
combo box with a wizard. To turn Control Wizards on or off, click the Control Wizards
tool in the toolbox.
The setting of the LimitToList property determines whether you can enter values that aren't
in the list.
The list can be single- or multiple-column, and the columns can appear with or without
headings.
CONTROLS - List Box
The list box control displays a list of values or alternatives. In many cases, it's quicker
and easier to select a value from a list than to remember a value to type. A list of choices
also helps ensure that the value that's entered in a field is correct.
The list in a list box consists of rows of data. Rows can have one or more columns, which
can appear with or without headings.
Remarks
If a multiple-column list box is bound, Microsoft Access stores the values from one of the
columns.
You can use an unbound list box to store a value that you can use with another control.
For example, you could use an unbound list box to limit the values in another list box
or in a custom dialog box. You could also use an unbound list box to find a record based
on the value you select in the list box.
If you don't have room on your form to display a list box, or if you want to be able to
type new values as well as select values from a list, use a combo box instead of a list box.
FUNCTION - CurrentDb
Example
The following example uses the CurrentDb function to return a Database object variable pointing to the current database. It then enumerates all the fields in the Employees table in that database.
Sub ListFields()
Dim dbs As Database, tdf As TableDef, fld As Field
' Return Database object variable pointing to current database.
Set dbs = CurrentDb
' Return TableDef object variable pointing to Employees table.
Set tdf = dbs.TableDefs!Employees
' Enumerate fields in Employees table.
For Each fld In tdf.Fields
Debug.Print fld.Name
Next fld
End Sub
PROPERTY - Data Type
You can use the DataType property to specify the type of data stored in a table field.
Each field can store data consisting of only a single data type.
Setting
The DataType property uses the following settings.
Setting Type of data Size
Text (Default) Text or combinations of text Up to 255 characters or
and numbers, as well as numbers that the length set by the FieldSize
don't requirecalculations, such as . property, whichever is less.
phonevnumbers. Access does not reserve space
for unused portions of a text field.
Memo Lengthy text or combinations of text. Up to 65,535 characters. (If the Memo
and numbers field is manipulated through DAO and
only text and numbers [not binary data]
will be stored in it, then the size of
the Memo field is limited by the size
of the database.)
Number Numeric data used in mathematical 1, 2, 4, or 8 bytes (16 bytes if the
calculations. For more information on FieldSize property is set to
how to set the specific Number type, Replication ID).
see the FieldSize property topic.
Date/Time Date and time values for the years 8 bytes.
100 through 9999.
Currency Currency values and numeric data used 8 bytes.
in mathematical calculations involving
data with one to four decimal places.
Accurate to 15 digits on the left side
of the decimal separator and to 4
digits on the right side.
AutoNumber A unique sequential (incremented by 1) 4 bytes (16 bytes if the FieldSize
number or random number assigned by property is set to Replication ID).
Microsoft Access whenever a new record
is added to a table. AutoNumber
fields can't be updated. For more
information, see the NewValues property
topic.
Yes/No Yes and No values and fields that 1 bit.
contain only one of two values
(Yes/No, True/False, or On/Off).
OLE Object An object (such as a Microsoft Excel Up to 1 gigabyte
spreadsheet, a Microsoft Word document, (limited by available disk space)
graphics, sounds, or other binary data)
linked to or embedded in a Microsoft
Access table.
Hyperlink Text or combinations of text and Each part of the three parts of
numbers stored as text and used as a a Hyperlink data type can contain
hyperlink address. A hyperlink address up to 2048 characters.
can have up to three parts:
displaytext - the text that appears in
a field or control.
address - the path to a file (UNC path)
or page (URL).
subaddress - a location within the file
or page.The easiest way to insert a
hyperlink address in a field or control
is to click Hyperlink on the Insert
menu. For more information, see Type
a hyperlink address in Form view or
Datasheet view.
Lookup Wizard Creates a field that allows you to The same size as the primary
choose a value from another table or key field used to perform the
from a list of values by using a list lookup, typically 4 bytes.
box or combo box. Clicking this
option starts the Lookup Wizard,
which creates a Lookup field. After
you complete the wizard, Microsoft
Access sets the data type based on
the values selected in the Wizard.
You can set this property only in the upper portion of table Design view.
In Visual Basic, you can use the DAO Type property to set a field's data type before
appending it to the Fields collection.
Remarks
Memo, Hyperlink, and OLE Object fields can't be indexed.
Tip
Use the Currency data type for a field requiring many calculations involving data with
one to four decimal places. Single and Double data type fields require floating-point
calculation. The Currency data type uses a faster fixed-point calculation.
Caution
Changing a field's data type after you enter data in a table causes a potentially lengthy
process of data conversion when you save the table. If the data type in a field conflicts
with a changed DataType property setting, you may lose some data.
Set the Format property to specify a predefined display format for Number, Date/Time,
Currency, and Yes/No data types.
For more information about choosing a field data type, see Chapter 4, "Working with
Variables, Data Types, and Constants," in Building Applications with Microsoft Access 97.
PROPERTY - DecimalPlaces
You can use the DecimalPlaces property to specify the number of decimal places
Microsoft Access uses to display numbers.
Setting
The DecimalPlaces property uses the following settings.
Setting Description Visual Basic
Auto (Default) Numbers appear as specified by the 255
Format property setting.
0 to 15 Digits to the right of the decimal separator appear 0 to 15
with the specified number of decimal places; digits
to the left of the decimal separator appear as
specified by the Format property setting.
You can set this property for text boxes and combo boxes by using the control's
property sheet and for table fields by using the table's property sheet. You can
also set this property in the Field Properties property sheet in query Design view.
Tip
You should set the DecimalPlaces property in the table's property sheet. A bound
control you create on a form or report inherits the DecimalPlaces property set in the
field in the underlying table or query, so you won't have to specify the property
individually for every bound control you create.
For controls, you can also set this property by using a macro or Visual Basic.
Note
The DecimalPlaces property setting has no effect if the Format property is blank
or is set to General Number.
Remarks
The DecimalPlaces property affects only the number of decimal places that display,
not how many decimal places are stored. To change the way a number is stored you
must change the FieldSize property in table Design view.
You can use the DecimalPlaces property to display numbers differently from the Format
property setting or from the way they are stored. For example, the Currency setting of
the Format property displays only two decimal places ($5.35). To display Currency
numbers with four decimal places (for example, $5.3523), set the DecimalPlaces property
to 4.
DATA - Find
There are many ways in Microsoft Access to find just the data you need, whether you're
looking for a particular value, one record, or a group of records.
· With the Find dialog box, you can locate specific records or find certain values within
fields. You can navigate through records as Microsoft Access finds each occurrence of
the item you're looking for. If you want to replace certain values that you find, use
the Replace dialog box instead.
· With filters, you can temporarily isolate and view a specific set of records to work
with while you have a form or datasheet displayed.
· With queries, you can work with a specific set of records that meet criteria you specify
from one or more tables in the database. You can work with this subset independent of a
specific form or datasheet by running the query.
Which method do you want to use to find data?
The Find dialog box
The Replace dialog box
A table, query or form filter
A query
EVENT - Activate, Deactivate
The Activate event occurs when a form or report receives the focus and becomes the
active window.
The Deactivate event occurs when a form or report loses the focus to a Table, Query,
Form, Report, Macro, or Module window, or to the Database window.
Note
The Deactivate event doesn't occur when a form or report loses the focus to a dialog
box, to a form for which the PopUp property is set to Yes, or to a window in another
application.
Remarks
To run a macro or event procedure when these events occur, set the OnActivate, or
OnDeactivate property to the name of the macro or to [Event Procedure].
You can make a form or report active by opening it, clicking it or a control on it,
or by using the SetFocus method in Visual Basic (for forms only).
The Activate event can occur only when a form or report is visible.
The Activate event occurs before the GotFocus event; the Deactivate event occurs after
the LostFocus event.
When you switch between two open forms, the Deactivate event occurs for the form being
switched from, and the Activate event occurs for the form being switched to. If the
forms contain no visible, enabled controls, the LostFocus event occurs for the first
form before the Deactivate event, and the GotFocus event occurs for the second form
after the Activate event.
When you first open a form, the following events occur in this order:
Open => Load => Resize => Activate => Current
When you close a form, the following events occur in this order:
Unload => Deactivate => Close
EVENT - Change
The Change event occurs when the contents of a text box or the text portion of a combo box
changes. It also occurs when you move from one page to another page in a tab control.
Examples of this event include entering a character directly in the text box or combo box
or changing the control's Text property setting by using a macro or Visual Basic.
Notes
Setting the value of a control by using a macro or Visual Basic doesn't trigger this event
for the control. You must type the data directly into the control, or set the control's
Text property.
This event applies only to controls on a form, not controls on a report.
Remarks
To run a macro or event procedure when this event occurs, set the OnChange property to the
name of the macro or to [Event Procedure].
By running a macro or event procedure when a Change event occurs, you can coordinate data
display among controls. You can also display data or a formula in one control and the results
in another control.
The Change event doesn't occur when a value changes in a calculated control or when you
select an item from the combo box list.
Note A Change event can cause a cascading event. This occurs when a macro or event procedure
that runs in response to the control's Change event alters the control's contents — for
example, by changing a property setting that determines the control's value, such as the Text
property for a text box. To prevent a cascading event:
If possible, avoid attaching a Change macro or event procedure to a control that alters the
control's contents.
Avoid creating two or more controls having Change events that affect each other — for example,
two text boxes that update each other.
Changing the data in a text box or combo box by using the keyboard causes keyboard events to
occur in addition to control events like the Change event. For example, if you move to a new
record and type an ANSI character in a text box in the record, the following events occur in
this order:
KeyDown -> KeyPress -> BeforeInsert -> Change -> KeyUp
The BeforeUpdate and AfterUpdate events for the text box or combo box control occur after you
have entered the new or changed data in the control and moved to another control (or clicked
Save Record on the Records menu), and therefore after all of the Change events for the control.
In combo boxes for which the LimitToList property is set to Yes, the NotInList event occurs
after you enter a value that isn't in the list and attempt to move to another control or save
the record. It occurs after all the Change events for the combo box. In this case, the
BeforeUpdate and AfterUpdate events for the combo box don't occur, because Microsoft Access
doesn't accept a value that is not in the list.
EVENTS - Load, Unload
The Load event occurs when a form is opened and its records are displayed.
The Unload event occurs after a form is closed but before it's removed from the screen.
When the form is reloaded, Microsoft Access redisplays the form and reinitializes the
contents of all its controls.
Remarks
To run a macro or event procedure when these events occur, set the OnLoad, or OnUnload
property to the name of the macro or to [Event Procedure].
The Load event is caused by user actions such as:
· Starting an application.
· Opening a form by clicking Open in the Database window.
· Running the OpenForm action in a macro.
The Unload event is caused by user actions such as:
· Clicking a Form window’s Close button or clicking Close on the File menu or
a form's Control menu.
· Running the Close action in a macro.
· Quitting an application by right-clicking the application's taskbar button and
then clicking Close.
· Quitting Windows while an application is running.
By running a macro or an event procedure when a form's Load event occurs, you can
specify default settings for controls, or display calculated data that depends on
the data in the form’s records.
By running a macro or an event procedure when a form's Unload event occurs, you can verify
that the form should be unloaded or specify actions that should take place when the form
is unloaded. You can also open another form or display a dialog box requesting the user's
name to make a log entry indicating who used the form.
When you first open a form, the following events occur in this order:
Open => Load => Resize => Activate => Current
If you're trying to decide whether to use the Open or Load event for your macro or
event procedure, one significant difference is that the Open event can be canceled,
but the Load event can't. For example, if you're dynamically building a record source
for a form in an event procedure for the form's Open event, you can cancel opening
the form if there are no records to display.
When you close a form, the following events occur in this order:
Unload => Deactivate => Close
The Unload event occurs before the Close event. The Unload event can be canceled, but
the Close event can't.
Note
When you create macros or event procedures for events related to the Load event, such
as Activate and GotFocus, be sure that they don't conflict (for example, make sure you
don't cause something to happen in one macro or procedure that is canceled in another)
and that they don't cause cascading events.
EVENT - Open, Close
The Open event occurs when a form is opened, but before the first record is displayed.
For reports, the event occurs before a report is previewed or printed.
The Close event occurs when a form or report is closed and removed from the screen.
Remarks
To run a macro or event procedure when these events occur, set the OnOpen or OnClose
property to the name of the macro or to [Event Procedure].
By running a macro or an event procedure when a form's Open event occurs, you can close
another window or move the focus to a particular control on a form. You can run a
macro or an event procedure that asks for information needed before the form or report
is opened or printed. For example, an Open macro or event procedure can open a custom
dialog box in which the user enters the criteria for the set of records to display on a
form or the date range to include for a report.
The Open event doesn't occur when you activate a form that's already open for example,
when you switch to the form from another window in Microsoft Access or use the OpenForm
action in a macro to bring the open form to the top. However, the Activate event does
occur in these situations.
When you open a form based on an underlying query, Microsoft Access runs the underlying
query for the form before it runs the Open macro or event procedure. However, when you
open a report based on an underlying query, Microsoft Access runs the Open macro or
event procedure before it runs the underlying query for the report. This enables the
user to specify criteria for the report before it opens for example, in a custom dialog
box you display when the Open event occurs.
If your application can have more than one form loaded at a time, use the Activate and
Deactivate events instead of the Open event to display and hide custom toolbars when
the focus moves to a different form.
The Open event occurs before the Load event, which is triggered when a form is opened
and its records are displayed.
When you first open a form, the following events occur in this order:
Open => Load => Resize => Activate => Current
The Close event occurs after the Unload event, which is triggered after the form is
closed but before it is removed from the screen.
When you close a form, the following events occur in this order:
Unload => Deactivate => Close
When the Close event occurs, you can open another window or request the user's name
to make a log entry indicating who used the form or report.
If you're trying to decide whether to use the Open or Load event for your macro or
event procedure, one significant difference is that the Open event can be canceled,
but the Load event can't. For example, if you're dynamically building a record source
for a form in an event procedure for the form's Open event, you can cancel opening the
form if there are no records to display. Similarly, the Unload event can be canceled,
but the Close event can't.
EXPRESSIONS - Entering.. in a property sheet, a design grid, or an action argument
If you are entering an expression that is longer than the standard input area in a
property sheet, a design grid, or an action argument, you can type the expression in
the Zoom box. To open the Zoom box, press SHIFT+F2 when the focus is where you want
to enter the expression.
When you enter an expression in a property sheet, a design grid, or an action argument,
Microsoft Access:
· Recognizes region-specific function names, property names, and list separators for
international versions.
· Inserts certain characters for you when the focus changes.
Depending on where you enter the expression, Microsoft Access automatically inserts:
· Brackets ([ ]) around form, report, field, or control names.
· Number signs (#) around dates.
· Double (") quotation marks around text.
Note
Calculated control expressions are always preceded by an equal sign (=).
Using functions and properties in international versions of Microsoft Access
When you enter a function or property in an expression in most international versions
of Microsoft Access:
· You can type its localized name (in your language) in a property sheet, a design grid,
or an action argument.
· You can use the list separator for your country when you specify more than one argument
for a function. You specify the list separator on the Number tab of the Regional Settings
Properties dialog box in Windows Control Panel. For most international versions, the
default list separator is a semicolon (;).
However, in Visual Basic for Applications code, you must type the English function or
property name and use a comma (,) as a list separator.
Entering object names
Brackets ([ ]) around a field, control, or property in an identifier indicate that the
element is the name of a table, query, form, report, field, or control.
When you type an object name in an identifier, you surround the name with brackets if it
contains a space or a special character, such as an underscore. If the name doesn't contain
a space or a special character, you can type the name without brackets. Microsoft Access
inserts brackets automatically (with two exceptions noted below).
For example, you can type the following expression as a setting for the ControlSource property
to calculate the sum of the values in the Freight and OrderAmount fields:
= Freight + OrderAmount
Microsoft Access displays the expression as follows:
= [Freight] + [OrderAmount]
Note
In a ValidationRule property setting or in a Criteria cell in the query design grid,
Microsoft Access doesn't always automatically insert brackets around a name. If you
are entering an object name, be sure to type brackets around it. Otherwise, Microsoft
Access may assume you are entering text and may insert double quotation marks.
Entering date/time values
Number signs (#) around an element of an expression indicate that the element is a
date/time value. Microsoft Access automatically evaluates a value surrounded by number
signs as a date/time value and lets you type the value in any common date or time format.
You don't have to type number signs around a date/time value in a validation expression or
a criteria expression for a field whose data type is Date/Time. You can type the value in
any common date or time format and Microsoft Access automatically inserts number signs around
the value.
Microsoft Access displays the value according to the settings in the Regional Settings
Properties dialog box in Windows Control Panel. You can change the output format of a date
by using the Format property.
Entering text
Double quotation marks around an element of an expression indicate that the element is text.
When you type text in a validation or criteria expression, you can type the text without
double quotation marks and Microsoft Access will insert them automatically.
For example, if you type the expression Paris, Microsoft Access displays the expression
as follows:
"Paris"
Format) from..
Queries: Handling floating-point, Currency, and Decimal Datatype in SQL
Author(s)
Joe Foster
Jet can be picky about decimal points. This can cause problems in countries where ","
is the decimal "point". Since Type specification characters such as @ don't work in
Access SQL, Jet will convert anything with a decimal point into a Double, possibly with
a loss of precision or even a type conversion failure.
This means that we have to use CCur or CDec within the SQL when dealing with those types,
but these functions always obey regional settings and won't always work with Str$. To get
around it, use the Format function.
"where salary = ccur(""" & Format$(MyCurrencyValue) & """)"
from..
Queries: Handling floating-point, Currency, and Decimal Datatype in SQL
Problem: My Report contains a field that is formatted. My total field in the Report
Footer has this for its control source: =Format(Sum([QryTotal]),"$#,###.##").
A control source in my report header for a total field will not work either:
=Format(Sum([QryTotal]),"$#,###.##") On my PC and our test PC, the format error I
described here does not occurr and the report runs beautifully and shows up in
preview print mode like it should. 'QryTotal' is a valid field in my query and it
runs fine when the query is run by itself. (this rpt has a query as it's data source)
Here, on the client PC, When I run the report, the report comes up & asks for a
Format, as if "Format" was a parameter.
from..
StartDate as a String instead of as a Date, and use
StartDate = Format(Start_Date, "mm/dd/yyyy")
instead.
Douglas J. Steel:
FORMAT - User Defined
Different Formats for Different Numeric Values (Format Function)
A user-defined format expression for numbers can have from one to four sections separated
by semicolons. If the format argument contains one of the named numeric formats, only one
section is allowed.
If you use The result is
One section only The format expression applies to all values.
Two sections The first section applies to positive values and zeros, the second
to negative values.
Three sections The first section applies to positive values, the second to negative
values, and the third to zeros.
Four sections The first section applies to positive values, the second to negative
values, the third to zeros, and the fourth to Null values.
The following example has two sections: the first defines the format for positive values and
zeros; the second section defines the format for negative values.
"$#,##0;($#,##0)"
If you include semicolons with nothing between them, the missing section is printed using the
format of the positive value. For example, the following format displays positive and negative
values using the format in the first section and displays "Zero" if the value is zero.
"$#,##0;;\Z\e\r\o"
The following table identifies characters you can use to create user-defined number formats:
Character
Description
None Display the number with no formatting.
(0) Digit placeholder. Display a digit or a zero. If the expression has a digit
in the position where the 0 appears in the format string, display it; otherwise,
display a zero in that position.If the number has fewer digits than there are
zeros (on either side of the decimal) in the format expression, display leading
or trailing zeros. If the number has more digits to the right of the decimal
separator than there are zeros to the right of the decimal separator in the
format expression, round the number to as many decimal places as there are zeros.
If the number has more digits to the left of the decimal separator than there are
zeros to the left of the decimal separator in the format expression, display the
extra digits without modification.
(#) Digit placeholder. Display a digit or nothing. If the expression has a digit in
the position where the # appears in the format string, display it; otherwise,
display nothing in that position.This symbol works like the 0 digit placeholder,
except that leading and trailing zeros aren't displayed if the number has the same
or fewer digits than there are # characters on either side of the decimal separator
in the format expression.
(.) Decimal placeholder. In some locales, a comma is used as the decimal separator.
The decimal placeholder determines how many digits are displayed to the left and
right of the decimal separator. If the format expression contains only number signs
to the left of this symbol, numbers smaller than 1 begin with a decimal separator.
To display a leading zero displayed with fractional numbers, use 0 as the first digit
placeholder to the left of the decimal separator. The actual character used as a
decimal placeholder in the formatted output depends on the Number Format recognized
by your system.
(%) Percentage placeholder. The expression is multiplied by 100. The percent character (%)
is inserted in the position where it appears in the format string.
(,) Thousand separator. In some locales, a period is used as a thousand separator. The
thousand separator separates thousands from hundreds within a number that has four
or more places to the left of the decimal separator. Standard use of the thousand
separator is specified if the format contains a thousand separator surrounded by
digit placeholders (0 or #). Two adjacent thousand separators or a thousand separator
immediately to the left of the decimal separator (whether or not a decimal is spcified)
means "scale the number by dividing it by 1000, rounding as needed." For example, you
can use the format string "##0,," to represent 100 million as 100. Numbers smaller
than 1 million are displayed as 0. Two adjacent thousand separators in any position
other than immediately to the left of the decimal separator are treated simply as
specifying the use of a thousand separator. The actual character used as the thousand
searator in the formatted output depends on the Number Format recognized by your system.
(:) Time separator. In some locales, other characters may be used to represent the time
separator. The time separator separates hours, minutes, and seconds when time values
are formatted. The actual character used as the time separator in formatted output is
determined by your system settings.
(/) Date separator. In some locales, other characters may be used to represent the date
separator. The date separator separates the day, month, and year when date values are
formatted. The actual character used as the date separator in formatted output is
determined by your system settings.
(E- E+ Scientific format. If the format expression contains at least one digit
e- e+) placeholder (0 or #) to the right of E-, E+, e-, or e+, the number is displayed in
scientific format and E or e is inserted between the number and its exponent. The
number of digit placeholders to the right determines the number of digits in the
exponent. Use E- or e- to place a minus sign next to negative exponents. Use E+ or e+
to place a minus sign next to negative exponents and a plus sign next to positive
exponents.
- + $ ( ) Display a literal character. To display a character other than one of those
listed, precede it with a backslash (\) or enclose it in double quotation marks (" ").
(\) Display the next character in the format string. To display a character that has
special meaning as a literal character, precede it with a backslash (\). The backslash
itself isn't displayed. Using a backslash is the same as enclosing the next character
in double quotation marks. To display a backslash, use two backslashes (\\).Examples
of characters that can't be displayed as literal characters are the date-formatting
and time-formatting characters (a, c, d, h, m, n, p, q, s, t, w, y, / and :), the numeric-formatting characters (#, 0, %, E, e, comma, and period), and the string-
formatting characters (@, &, <, >, and !).
("ABC") Display the string inside the double quotation marks (" "). To include a string in
format from within code, you must use Chr(34) to enclose the text (34 is the character
code for a quotation mark (")).
FUNCTION - Create a custom..
1 Open a new module.
To open a new standard module, click the Modules tab in the Database window,
and then click New. To open an existing standard module, click the Modules tab,
select the module you want to open, and then click Design.
To open a form module or report module, open the form or report in Design
view, and then click the Code icon on the tool bar.
To open a new class module that isn't associated with a form or report, in
the Database window click Class Module on the Insert menu. To open an existing class
module, click the Modules tab in the Database window, select the module you want
to open, and then click Design.
2 Declare the function by typing the Function statement.
3 Type a function name, immediately followed by any function arguments in parentheses.
For example, the following declaration for the IsLoaded function specifies strFormName
as an argument:
Function IsLoaded(strFormName As String) As Boolean
4 Add the Visual Basic for Applications code that performs the operation or calculation
that you want the function to perform.
FUNCTION - Format
Returns a Variant (String) containing an expression formatted according to instructions
contained in a format expression.
Syntax
Format(expression[, format[, firstdayofweek[, firstweekofyear]]])
The Format function syntax has these parts:
Part Description
expression Required. Any valid expression.
format Optional. A valid named or user-defined format expression.
firstdayofweek Optional. A constant that specifies the first day of the week.
firstweekofyear Optional. A constant that specifies the first week of the year.
Settings
The firstdayofweek argument has these settings:
Constant Value Description
vbUseSystem 0 Use NLS API setting.
VbSunday 1 Sunday (default)
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday
The firstweekofyear argument has these settings:
Constant Value Description
vbUseSystem 0 Use NLS API setting.
vbFirstJan1 1 Start with week in which January 1 occurs (default).
vbFirstFourDays 2 Start with the first week that has at least four days in the year.
vbFirstFullWeek 3 Start with the first full week of the year.
Remarks
To Format Do This
Numbers Use predefined named numeric formats or create
user-defined numeric formats.
Dates and times Use predefined named date/time formats or create
user-defined date/time formats.
Date and time serial numbers Use date and time formats or numeric formats.
Strings Create your own user-defined string formats.
If you try to format a number without specifying format, Format provides functionality
similar to the Str function, although it is internationally aware. However, positive
numbers formatted as strings using Format don't include a leading space reserved for
the sign of the value; those converted using Str retain the leading space.
Examples
This example shows various uses of the Format function to format values using both
named formats and user-defined formats. For the date separator (/), time separator (:),
and AM/ PM literal, the actual formatted output displayed by your system depends on
the locale settings on which the code is running. When times and dates are displayed
in the development environment, the short time format and short date format of the
code locale are used. When displayed by running code, the short time format and short
date format of the system locale are used, which may differ from the code locale. For
this example, English/U.S. is assumed.
MyTime and MyDate are displayed in the development environment using current system
short time setting and short date setting.
Dim MyTime, MyDate, MyStr
MyTime = #17:04:23#
MyDate = #January 27, 1993#
' Returns current system time in the system-defined long time format.
MyStr = Format(Time, "Long Time")
' Returns current system date in the system-defined long date format.
MyStr = Format(Date, "Long Date")
MyStr = Format(MyTime, "h:m:s") ' Returns "17:4:23".
MyStr = Format(MyTime, "hh:mm:ss AMPM") ' Returns "05:04:23 PM".
MyStr = Format(MyDate, "dddd, mmm d yyyy") ' Returns "Wednesday, Jan 27 1993".
' If format is not supplied, a string is returned.
MyStr = Format(23) ' Returns "23".
' User-defined formats.
MyStr = Format(5459.4, "##,##0.00") ' Returns "5,459.40".
MyStr = Format(334.9, "###0.00") ' Returns "334.90".
MyStr = Format(5, "0.00%") ' Returns "500.00%".
MyStr = Format("HELLO", "<") ' Returns "hello".
MyStr = Format("This is it", ">") ' Returns "THIS IS IT"
FUNCTION Statement (Access 97)
In Microsoft Access, a public Function procedure is available to all other procedures in
the current database and in referencing Microsoft Access databases. However, it is not
available to any other applications.
If you declare a Function procedure as private in any module by preceding it with the
Private keyword, that procedure is available only to other procedures in the same module.
If a Function procedure is declared as public within a private module, such as a class
module, then the procedure is available to all other procedures in that database, but is
not available to other Microsoft Access databases.
FUNCTION Statement (General)
Declares the name, arguments, and code that form the body of a Function procedure.
Syntax
[Public | Private] [Static] Function name [(arglist)] [As type]
[statements]
[name = expression]
[Exit Function]
[statements]
[name = expression]
End Function
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,
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.
The arglist argument has the following syntax and parts:
[Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue]
Part Description
Optional Optional. Indicates that an argument is not required. If used, all
subsequent arguments in arglist must also be optional and declared
using the Optional keyword. Optional can't be used for any argument
if ParamArray is used.
ByVal Optional. Indicates that the argument is passed by value.
ByRef Optional. Indicates that the argument is passed by reference. ByRef
is the default in Visual Basic.
ParamArray Optional. Used only as the last argument in arglist to indicate that
the final argument is an Optional array of Variant elements. The
ParamArray keyword allows you to provide an arbitrary number of
arguments. It may not be used with ByVal, ByRef, or Optional.
varname Required. Name of the variable representing the argument; follows
standard variable naming conventions.
type Optional. Data type of the argument passed to the procedure; may be Byte,
Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently
supported) Date, String (variable length only), Object, Variant. If the
parameter is not Optional, a user-defined type or an object type may also
be specified.
defaultvalue Optional. Any constant or constant expression. Valid for Optional
parameters only. If the type is an Object, an explicit default value
can only be Nothing.
Remarks
If not explicitly specified using either Public or Private, Function procedures are
public by default. If Static is not used, the value of local variables is not preserved
between calls.
Caution
Function procedures can be recursive; that is, they can call themselves to perform a given
task. However, recursion can lead to stack overflow. The Static keyword is usually not used
with recursive Function procedures.
All executable code must be in procedures. You can't define a Function procedure inside
another Function, Sub, or Property procedure.
The Exit Function statement causes an immediate exit from a Function procedure. Program
execution continues with the statement following the statement that called the Function
procedure. Any number of Exit Function statements can appear anywhere in a Function
procedure.
Like a Sub procedure, a Function procedure is a separate procedure that can take arguments,
perform a series of statements, and change the values of its arguments. However, unlike a
Sub procedure, you can use a Function procedure on the right side of an expression in the
same way you use any intrinsic function, such as Sqr, Cos, or Chr, when you want to use the
value returned by the function.
You call a Function procedure using the function name, followed by the argument list in
parentheses, in an expression. See the Call statement for specific information on how to
call Function procedures.
To return a value from a function, assign the value to the function name. Any number of
such assignments can appear anywhere within the procedure. If no value is assigned to
name, the procedure returns a default value: a numeric function returns 0, a string
function returns a zero-length string (""), and a Variant function returns Empty. A
function that returns an object reference returns Nothing if no object reference is
assigned to name (using Set) within the Function.
The following example shows how to assign a return value to a function named BinarySearch.
In this case, False is assigned to the name to indicate that some value was not found.
Function BinarySearch(. . .) As Boolean
. . .
' Value not found. Return a value of False.
If lower > upper Then
BinarySearch = False
Exit Function
End If
. . .
End Function
Variables used in Function procedures fall into two categories: those that are
explicitly declared within the procedure and those that are not. Variables that
are explicitly declared in a procedure (using Dim or the equivalent) are always
local to the procedure. Variables that are used but not explicitly declared in a
procedure are also local unless they are explicitly declared at some higher level
outside the procedure.
Caution
A procedure can use a variable that is not explicitly declared in the procedure,
but a naming conflict can occur if anything you defined at the module level has
the same name. If your procedure refers to an undeclared variable that has the
same name as another procedure, constant, or variable, it is assumed that your
procedure refers to that module-level name. Explicitly declare variables to avoid
this kind of conflict. You can use an Option Explicit statement to force
explicit declaration of variables.
Caution
Visual Basic may rearrange arithmetic expressions to increase internal efficiency.
Avoid using a Function procedure in an arithmetic expression when the function
changes the value of variables in the same expression.
Examples
The following example uses the Function statement to declare the name, arguments, and
code that form the body of a Function procedure. The second example uses the ParamArray
keyword. The last example uses hard-typed, initialized Optional arguments.
' The following user-defined function returns the square root of the
' argument passed to it.
Function CalculateSquareRoot(NumberArg As Double) As Double
If NumberArg < 0 Then ' Evaluate argument.
Exit Function ' Exit to calling procedure.
Else
CalculateSquareRoot = Sqr(NumberArg) ' Return square root.
End If
End Function
Using the ParamArray keyword enables a function to accept a variable number of arguments.
In the following definition, FirstArg is passed by value.
Function CalcSum(ByVal FirstArg As Integer, ParamArray OtherArgs())
Dim ReturnValue
' If the function is invoked as follows:
ReturnValue = CalcSum(4, 3 ,2 ,1)
' Local variables are assigned the following values: FirstArg = 4,
' OtherArgs(1) = 3, OtherArgs(2) = 2, and so on, assuming default
' lowerbound for arrays = 1.
Optional arguments can now have default values and types other than Variant.
' If a function's arguments are defined as follows:
Function MyFunc(MyStr As String, Optional MyArg1 As _ Integer = 5, Optional MyArg2 = "Dolly")
Dim RetVal
' The function can be invoked as follows:
RetVal = MyFunc("Hello", 2, "World") ' All 3 arguments supplied.
RetVal = MyFunc("Test", , 5) ' Second argument omitted.
' Arguments one and three using named-arguments.
RetVal = MyFunc(MyStr:="Hello ", MyArg1:=7)
FUNCTION - IIf
Returns one of two parts, depending on the evaluation of an expression.
Syntax
IIf(expr, truepart, falsepart)
The IIf function syntax has these named arguments:
Part Description
expr Required. Expression you want to evaluate.
truepart Required. Value or expression returned if expr is True.
falsepart Required. Value or expression returned if expr is False.
Remarks
IIf always evaluates both truepart and falsepart, even though it returns only one of
them. Because of this, you should watch for undesirable side effects. For example,
if evaluating falsepart results in a division by zero error, an error occurs even if
expr is True.
Example (Access)
This example uses the IIf function to evaluate an OrderAmount field and returns the
word "Large" if the amount is greater than 1000; otherwise, it returns the word
"Small". You can enter the following expression in the ControlSource property of a
calculated control.
= IIf([OrderAmount] > 1000, "Large", "Small")
Example (Function)
This example uses the IIf function to evaluate the TestMe parameter of the CheckIt
procedure and returns the word "Large" if the amount is greater than 1000; otherwise,
it returns the word "Small".
Function CheckIt (TestMe As Integer)
CheckIt = IIf(TestMe > 1000, "Large", "Small")
End Function
This statement writes a sentence that leaves out any null entries:
IIF (IsNull([Age]), "", "The age is " & [Age] & " years old,") & _
IIF (IsNull([DistillDate]), "", " distilled in " & [DistillDate])
FUNCTION - Nz
You can use the Nz function to return zero, a zero-length string (" "), or another
specified value when a Variant is Null. For example, you can use this function to convert
a Null value to another value and prevent it from propagating through an expression.
Syntax
Nz(variant[, valueifnull])
The Nz function has the following arguments.
Argument Description
variant A variable of data type Variant.
valueifnull Optional (unless used in a query). A Variant that supplies a value to be
returned if the variant argument is Null. This argument enables you to return
a value other than zero or a zero-length string. If you use the Nz function
in an expression in a query without using the ValueIfNull argument, the
results will be empty in the fields that contain null values
If the value of the variant argument is Null, the Nz function returns the number zero or
a zero-length string, depending on whether the context indicates the value should be a
number or a string. If the optional valueifnull argument is included, then the Nz function
will return the value specified by that argument if the variant argument is Null.
If the value of variant isn't Null, then the Nz function returns the value of variant.
Remarks
The Nz function is useful for expressions that may include Null values. To force an
expression to evaluate to a non-Null value even when it contains a Null value, use the Nz
function to return a zero, a zero-length string, or a custom return value.
For example, the expression 2 + varX will always return a Null value when the Variant
varX is Null. However, 2 + Nz(varX) returns 2.
You can often use the Nz function as an alternative to the IIf function. For example,
in the following code, two expressions including the IIf function are necessary to return
the desired result. The first expression including the IIf function is used to check the
value of a variable and convert it to zero if it is Null.
varTemp = IIf(IsNull(varFreight), 0, varFreight)
varResult = IIf(varTemp > 50, "High", "Low")
In the next example, the Nz function provides the same functionality as the first
expression, and the desired result is achieved in one step rather than two.
varResult = IIf(Nz(varFreight) > 50, "High", "Low")
If you supply a value for the optional argument valueifnull, that value will be returned
when variant is Null. By including this optional argument, you may be able to avoid the
use of an expression containing the IIf function. For example, the following expression
uses the IIf function to return a string if the value of varFreight is Null.
varResult = IIf(IsNull(varFreight), "No Freight Charge", varFreight)
In the next example, the optional argument supplied to the Nz function provides the string
to be returned if varFreight is Null.
varResult = Nz(varFreight, "No Freight Charge")
Example
The following example evaluates a control on a form and returns one of two strings based
on the control's value. If the value of the control is Null, the procedure uses the Nz
function to convert a Null value to a zero-length string.
Sub CheckValue()
Dim frm As Form, ctl As Control
Dim varResult As Variant
' Return Form object variable pointing to Orders form.
Set frm = Forms!Orders
' Return Control object variable pointing to ShipRegion.
Set ctl = frm!ShipRegion
' Choose result based on value of control.
varResult = IIf(Nz(ctl.Value) = "", "No value", "Value is " & ctl.Value)
' Display result.
MsgBox varResult
End Sub
FUNCTIONS - Type Conversion
Each function coerces an expression to a specific data type.
Syntax
CBool(expression)
CByte(expression)
CCur(expression)
CDate(expression)
CDbl(expression)
CDec(expression)
CInt(expression)
CLng(expression)
CSng(expression)
CVar(expression)
CStr(expression)
expression argument - any string expression or numeric expression.
Return Types
The function name determines the return type as shown in the following:
Function Return Type Range for expression argument
CBool Boolean Any valid string or numeric expression.
CByte Byte 0 to 255.
CCur Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
CDate Date Any valid date expression.
CDbl Double -1.79769313486232E308 to -4.94065645841247E-324
for negative values;
4.94065645841247E-324 to 1.79769313486232E308
for positive values.
CDec Decimal +/-79,228,162,514,264,337,593,543,950,335
for zero-scaled numbers, that is,
numbers with no decimal places.
For numbers with 28 decimal places, the range is
+/-7.9228162514264337593543950335.
The smallest possible non-zero number is
0.0000000000000000000000000001.
CInt Integer -32,768 to 32,767; fractions are rounded.
CLng Long -2,147,483,648 to 2,147,483,647; fractions are rounded.
CSng Single -3.402823E38 to -1.401298E-45 for negative values;
1.401298E-45 to 3.402823E38 for positive values.
CVar Variant Same range as Double for numerics.
Same range as String for non-numerics.
CStr String Returns for CStr depend on the expression argument.
Remarks
If the expression passed to the function is outside the range of the data type being
converted to, an error occurs.
In general, you can document your code using the data-type conversion functions to show
that the result of some operation should be expressed as a particular data type rather
than the default data type. For example, use CCur to force currency arithmetic in cases
where single-precision, double-precision, or integer arithmetic normally would occur.
You should use the data-type conversion functions instead of Val to provide internationally
aware conversions from one data type to another. For example, when you use CCur, different
decimal separators, different thousand separators, and various currency options are properly
recognized depending on the locale setting of your computer.
When the fractional part is exactly 0.5, CInt and CLng always round it to the nearest even
number. For example, 0.5 rounds to 0, and 1.5 rounds to 2. CInt and CLng differ from the Fix
and Int functions, which truncate, rather than round, the fractional part of a number. Also,
Fix and Int always return a value of the same type as is passed in.
Use the IsDate function to determine if date can be converted to a date or time. CDate
recognizes date literals and time literals as well as some numbers that fall within the
range of acceptable dates. When converting a number to a date, the whole number portion
is converted to a date. Any fractional part of the number is converted to a time of day,
starting at midnight.
CDate recognizes date formats according to the locale setting of your system. The correct
order of day, month, and year may not be determined if it is provided in a format other
than one of the recognized date settings. In addition, a long date format is not recognized
if it also contains the day-of-the-week string.
A CVDate function is also provided for compatibility with previous versions of Visual
Basic. The syntax of the CVDate function is identical to the CDate function, however,
CVDate returns a Variant whose subtype is Date instead of an actual Date type. Since there
is now an intrinsic Date type, there is no further need for CVDate. The same effect can
be achieved by converting an expression to a Date, and then assigning it to a Variant.
This technique is consistent with the conversion of all other intrinsic types to their
equivalent Variant subtypes.
Note
The CDec function does not return a discrete data type; instead, it always returns a Variant
whose value has been converted to a Decimal subtype.
Example (CInt)
This example uses the CInt function to convert a value to an Integer.
Dim MyDouble, MyInt
MyDouble = 2345.5678 ' MyDouble is a Double.
MyInt = CInt(MyDouble) ' MyInt contains 2346.
Example (CLng)
This example uses the CLng function to convert a value to a Long.
Dim MyVal1, MyVal2, MyLong1, MyLong2
MyVal1 = 25427.45: MyVal2 = 25427.55 ' MyVal1, MyVal2 are Doubles.
MyLong1 = CLng(MyVal1) ' MyLong1 contains 25427.
MyLong2 = CLng(MyVal2) ' MyLong2 contains 25428.
Example (CSng)
This example uses the CSng function to convert a value to a Single.
Dim MyDouble1, MyDouble2, MySingle1, MySingle2
' MyDouble1, MyDouble2 are Doubles.
MyDouble1 = 75.3421115: MyDouble2 = 75.3421555
MySingle1 = CSng(MyDouble1) ' MySingle1 contains 75.34211.
MySingle2 = CSng(MyDouble2) ' MySingle2 contains 75.34216.
Example (CStr)
This example uses the CStr function to convert a numeric value to a String.
Dim MyDouble, MyString
MyDouble = 437.324 ' MyDouble is a Double.
MyString = CStr(MyDouble) ' MyString contains "437.324".
Example (CVar)
This example uses the CVar function to convert an expression to a Variant.
Dim MyInt, MyVar
MyInt = 4534 ' MyInt is an Integer.
MyVar = CVar(MyInt & "000") ' MyVar contains the string
' 4534000.
KEYWORD - Nothing
The Nothing keyword is used to disassociate an object variable from an actual object.
Use the Set statement to assign Nothing to an object variable. For example:
Set MyObject = Nothing
Several object variables can refer to the same actual object. When Nothing is assigned to
an object variable, that variable no longer refers to an actual object. When several object
variables refer to the same object, memory and system resources associated with the object
to which the variables refer are released only after all of them have been set to Nothing,
either explicitly using Set, or implicitly after the last object variable set to Nothing
goes out of scope.
MACROS - AutoKeys
Assign Action(s) |
Key Combinations |
Assign an action or set of actions to a key
You can assign an action or set of actions to a specific key or key combination by
creating an AutoKeys macro group. When you press the key or key combination, Microsoft
Access carries out the action.
Database window -> Macros tab -> New -> toolbar)Macro Names
In the Macro Name column, type the key or key combination to which you want to
assign the action or set of actions.
For information on the key combinations you can use to make key assignments, click .
5 Add the action or set of actions you want the key or key combination to carry out.
For example, you could add a RunMacro action that runs the Print Current Record
macro when CTRL+P is pressed.
6 Repeat steps 4 and 5 for any other key assignments you want to make.
7 Save the macro group with the name AutoKeys.
The new key assignments are in effect as soon as you save the macro group and each time
you open the database.
Note If you assign a set of actions to a key combination that is already being used by
Microsoft Access (for example, CTRL+C is the key combination for Copy), the actions you
assign this key combination replace the Microsoft Access key assignment.
AutoKeys key combinations
The following table shows the key combinations you can use to make key assignments in
an AutoKeys macro group. These key combinations are a subset of the syntax used in the
SendKeys statement in Visual Basic.
SendKeys syntax Key combination
^A or ^4 CTRL+Any letter or number key
{F1} Any function key
^{F1} CTRL+Any function key
+{F1} SHIFT+Any function key
{INSERT} INS
^{INSERT} CTRL+INS
+{INSERT} SHIFT+INS
{DELETE} or {DEL} DEL
^{DELETE} or ^{DEL} CTRL+DEL
+{DELETE} or +{DEL} SHIFT+DEL
METHOD - Add
Adds a member to a Collection object.
Syntax
object.Add item, key, before, after
The Add method syntax has the following object qualifier and named arguments:
Part Description
object Required. An object expression that evaluates to an object in the Applies To list.
item Required. An expression of any type that specifies the member to add to the
collection.
key Optional. A unique string expression that specifies a key string that can be used,
instead of a positional index, to access a member of the collection.
before Optional. An expression that specifies a relative position in the collection. The
member to be added is placed in the collection before the member identified by the
before argument. If a numeric expression, before must be a number from 1 to the
value of the collection's Count property. If a string expression, before must
correspond to the key specified when the member being referred to was added to the
collection. You can specify a before position or an after position, but not both.
after Optional. An expression that specifies a relative position in the collection. The
member to be added is placed in the collection after the member identified by the
after argument. If numeric, after must be a number from 1 to the value of the
collection's Count property. If a string, after must correspond to the key
specified when the member referred to was added to the collection. You can specify
a before position or an after position, but not both.
Remarks
Whether the before or after argument is a string expression or numeric expression, it must
refer to an existing member of the collection, or an error occurs.
An error also occurs if a specified key duplicates the key for an existing member of the
collection.
Example
The following example uses the Add method to add one standard module to the VBComponents
collection.
Application.VBE.VBProjects(1).VBComponents.Add(vbext_ct_StdModule)
Example
This example uses the Add method to add Inst objects (instances of a class called Class1
containing a Public variable InstanceName) to a collection called MyClasses. To see how
this works, insert a class module and declare a public variable called InstanceName at
module level of Class1 (type Public InstanceName) to hold the names of each instance.
Leave the default name as Class1. Copy and paste the following code into the Form_Load event
procedure of a form module.
Dim MyClasses As New Collection ' Create a Collection object.
Dim Num As Integer ' Counter for individualizing keys.
Dim Msg
Dim TheName ' Holder for names user enters.
Do
' Create a new instance of Class1.
Dim Inst As New Class1
' Increment Num, then get a name.
Num = Num + 1
Msg = "Please enter a name for this object." & Chr(13) _
& "Press Cancel to see names in collection."
TheName = InputBox(Msg, "Name the Collection Items")
' Put name in object instance.
Inst.InstanceName = TheName
' If user entered name, add it to the collection.
If Inst.InstanceName <> "" Then
' Add the named object to the collection.
MyClasses.Add item := Inst, key := CStr(Num)
End If
' Clear the current reference in preparation for next one.
Set Inst = Nothing
Loop Until TheName = ""
For Each x In MyClasses
MsgBox x.instancename, , "Instance Name"
Next
METHOD - AddFromFile
The AddFromFile method adds the contents of a text file to a Module object. The Module
object may represent a standard module or a class module.
Syntax
object.AddFromFile filename
The AddFromFile method has the following arguments.
Argument Description
object A Module object.
filename The name and full path of a text (.txt) file or another file that stores
text in an ANSI format.
Remarks
The AddFromFile method places the contents of the specified text file immediately after
the Declarations section and before the first procedure in the module if it contains
other procedures.
The AddFromFile method enables you to import code or comments stored in a text file.
In order to add the contents of a file to a form or report module, the form or report must
be open in form Design view or report Design view. In order to add the contents of a file
to a standard module or class module, the module must be open.
Example
The following function uses the AddFromString and AddFromFile methods to add a string
and the contents of a text file to a standard module:
Function AddTextToModule(strModuleName As String,strFileName As String,strText As String) As Boolean
Dim mdl As Module
On Error GoTo Error_AddTextToModule
DoCmd.OpenModule strModuleName
Set mdl = Modules(strModuleName)
mdl.AddFromFile strFileName
mdl.AddFromString strText
AddTextToModule = True
Exit_AddTextToModule:
Exit Function
Error_AddTextToModule:
MsgBox Err & ": " & Err.Description
AddTextToModule = False
Resume Exit_AddTextToModule
End Function
You could call the preceding function from a procedure such as the following. Create a
text file called Functions.txt, add some Visual Basic procedures, and save it in the
My Documents directory. Then paste both the preceding procedure and the following procedure
into a new standard module in the Northwind sample database. Run the following procedure:
Sub AddFunctionsFromText()
Dim strModuleName As String, strFileName As String
Dim strText As String
strModuleName = "Utility Functions"
strFileName = "C:\My Documents\Functions.txt"
strText = "Public intX As Integer" & vbCrLf _
& "Const conPathName As String = " _
& """C:\Program Files\Microsoft Office\Office\Samples\"""
If AddTextToModule(strModuleName, strFileName, strText) = True Then
Debug.Print "String and file contents added successfully."
Else
Debug.Print "String and file contents: Unable to Add."
End If
End Sub
The next example creates a new form and adds a string and the contents of the Functions.txt
file to its module. Run the following procedure from a standard module:
Sub AddTextToFormModule()
Dim frm As Form, mdl As Module
Set frm = CreateForm
Set mdl = frm.Module
mdl.AddFromString "Public intY As Integer"
mdl.AddFromFile "C:\My Documents\Functions.txt"
End Sub
METHOD - Append (DAO)
Adds a new DAO object to a collection.
Syntax
collection.Append object
The Append method syntax has these parts.
Part Description
collection An object variable that represents any collection that can accept new
objects (for limitations, see the table at the end of this topic).
object An object variable that represents the object being appended, which must be
of the same type as the elements of collection.
Remarks
You can use the Append method to add a new table to a database, add a field to a table, and
add a field to an index.
The appended object becomes a persistent object, stored on disk, until you delete it by
using the Delete method. If collection is a Workspaces collection (which is stored only
in memory), the object is active until you remove it by using the Close method.
The addition of a new object occurs immediately, but you should use the Refresh method
on any other collections that may be affected by changes to the database structure.
If the object you're appending isn’t complete (such as when you haven’t appended any Field
objects to a Fields collection of an Index object before it’s appended to an Indexes
collection) or if the properties set in one or more subordinate objects are incorrect,
using the Append method causes an error. For example, if you haven’t specified a field
type and then try to append the Field object to the Fields collection in a TableDef object,
using the Append method triggers a run-time error.
The following table lists some limitations of the Append method. The object in the first
column is an object containing the collection in the second column. The third column
indicates whether you can append an object to that collection (for example, you can never
append a Container object to the Containers collection of a Database object).
Object Collection Can you append new objects?
DBEngine Workspaces Yes
DBEngine Errors No. New Error objects are automatically appended when
they occur.
Workspace Connections No. Using the OpenConnection method automatically appends
new objects.
Workspace Databases No. Using the OpenDatabase method automatically appends
new objects.
Workspace Groups Yes
Workspace Users Yes
Connection QueryDefs No. Using the CreateQueryDef method automatically appends
new objects.
Connection Recordsets No. Using the OpenRecordset method automatically appends
new objects.
Database Containers No
Database QueryDefs Only when the QueryDef object is a new, unappended object
created with no name. See the CreateQueryDef method for
details.
Database Recordsets No. Using the OpenRecordset method automatically appends
new objects.
Database Relations Yes
Database TableDefs Yes
Group Users Yes
User Groups Yes
Container Documents No
QueryDef Fields No
QueryDef Parameters No
Recordset Fields No
Relation Fields Yes
TableDef Fields Only when Updatable property of the TableDef object
is set to True, or unappended TableDef object.
TableDef Indexes Only when Updatable property of the TableDef is set to
True, or unappended TableDef object
Index Fields Only when the Index object is a new, unappended object.
Database, Properties Only when the Database, Field, Index, QueryDef, or TableDef
Field, object is in a Microsoft Jet workspace.
Index,
QueryDef,
TableDef
DBEngine, Properties No
Parameter,
Recordset,
Workspace
Example (DAO)
This example uses either the Append method or the Delete method to modify the Fields
collection of a TableDef. The AppendDeleteField procedure is required for this procedure
to run.
Sub AppendX()
Dim dbsNorthwind As Database
Dim tdfEmployees As TableDef
Dim fldLoop As Field
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
Set tdfEmployees = dbsNorthwind.TableDefs!Employees
' Add three new fields.
AppendDeleteField tdfEmployees, "APPEND", _
"E-mail", dbText, 50
AppendDeleteField tdfEmployees, "APPEND", _
"Http", dbText, 80
AppendDeleteField tdfEmployees, "APPEND", _
"Quota", dbInteger, 5
Debug.Print "Fields after Append"
Debug.Print , "Type", "Size", "Name"
' Enumerate the Fields collection to show the new fields.
For Each fldLoop In tdfEmployees.Fields
Debug.Print , fldLoop.Type, fldLoop.Size, fldLoop.Name
Next fldLoop
' Delete the newly added fields.
AppendDeleteField tdfEmployees, "DELETE", "E-mail"
AppendDeleteField tdfEmployees, "DELETE", "Http"
AppendDeleteField tdfEmployees, "DELETE", "Quota"
Debug.Print "Fields after Delete"
Debug.Print , "Type", "Size", "Name"
' Enumerate the Fields collection to show that the new
' fields have been deleted.
For Each fldLoop In tdfEmployees.Fields
Debug.Print , fldLoop.Type, fldLoop.Size, fldLoop.Name
Next fldLoop
dbsNorthwind.Close
End Sub
Sub AppendDeleteField(tdfTemp As TableDef, _
strCommand As String, strName As String, _
Optional varType, Optional varSize)
With tdfTemp
' Check first to see if the TableDef object is updatable.
' If it isn't, control is passed back to the calling procedure.
If .Updatable = False Then
MsgBox "TableDef not Updatable! " & _
"Unable to complete task."
Exit Sub
End If
' Depending on the passed data, append or delete a field to the
' Fields collection of the specified TableDef object.
If strCommand = "APPEND" Then
.Fields.Append .CreateField(strName, varType, varSize)
Else
If strCommand = "DELETE" Then .Fields.Delete strName
End If
End With
End Sub
Example (Access)
The following example defines a new Field object and appends it to the Fields collection of a TableDef object:
Sub NewField()
Dim dbs As Database, tdf As TableDef, fld As Field
' Return reference to current database.
Set dbs = CurrentDb
Set tdf = dbs.TableDefs!Employees
' Create new field in Employees table.
Set fld = tdf.CreateField("SocialSecurity#", dbText, 11)
' Append field and refresh collection.
tdf.Fields.Append fld
tdf.Fields.Refresh
Set dbs = Nothing
End Sub
Example (Excel)
This example creates a new database, Nwindex.mdb. The example attaches two tables from
the C:\Program Files\Common Files\Microsoft Shared\MSquery folder to the database. (In
Windows NT, the two tables are located in the C:\Windows\Msapps\Msquery folder.)
Dim nWindEx As Database, customerTable As TableDef, supplierTable As TableDef
Dim dataSource As String
dataSource = _
"dBASE IV;DATABASE=C:\Program Files\Common Files\Microsoft Shared\MSquery"
appPath = Application.Path
Set nWindEx = Workspaces(0).CreateDatabase(Application.Path _
& "\NWINDEX.MDB", dbLangGeneral)
Set customerTable = nWindEx.CreateTableDef("Customer")
customerTable.Connect = dataSource
customerTable.SourceTableName = "Customer"
nWindEx.TableDefs.Append customerTable
Set supplierTable = nWindEx.CreateTableDef("Supplier")
supplierTable.Connect = dataSource
supplierTable.SourceTableName = "Supplier"
nWindEx.TableDefs.Append supplierTable
MsgBox "The database " & nWindEx.Name & " has been created."
nWindEx.Close
METHOD - ApplyFilter
The ApplyFilter method carries out the ApplyFilter action in Visual Basic. For more
information on how the action and its arguments work, see the action topic.
Syntax
DoCmd.ApplyFilter [filtername][, wherecondition]
The ApplyFilter method has the following arguments.
Argument Description
filtername A string expression that's the valid name of a query in the current database.
wherecondition A string expression that's a valid SQL WHERE clause without the word WHERE.
Remarks
You must include at least one of the two ApplyFilter method arguments. If you enter a value
for both arguments, the wherecondition argument is applied to the filter.
The maximum length of the wherecondition argument is 32,768 characters (unlike the Where
Condition action argument in the Macro window, whose maximum length is 256 characters).
If you specify the wherecondition argument and leave the filtername argument blank, you must
include the filtername argument's comma.
Example
The following example uses the ApplyFilter method to display only records that contain
the name King in the LastName field:
DoCmd.ApplyFilter , "LastName = 'King'"
METHOD - Close
Closes an open DAO object.
Syntax
object.Close
The object placeholder is an object variable that represents an open Connection, Database,
Recordset, or Workspace object.
Remarks
Closing an open object removes it from the collection to which it's appended. Any attempt
to close the default workspace is ignored.
If the Connection, Database, Recordset, or Workspace object named by object is already
closed when you use Close, a run-time error occurs.
Caution
If you exit a procedure that declares Connection, Database, or Recordset objects, those
objects are closed, all pending transactions are rolled back, and any pending edits to
your data are lost.
If you try to close a Connection or Database object while it has any open Recordset
objects, the Recordset objects will be closed and any pending updates or edits will be
canceled. Similarly, if you try to close a Workspace object while it has any open
Connection or Database objects, those Connection and Database objects will be closed,
which will close their Recordset objects.
Using the Close method on either an original or cloned Recordset object doesn't affect
the other Recordset object.
To remove objects from updatable collections other than the Connections, Databases,
Recordsets, and Workspaces collections, use the Delete method on those collections.
You can't add a new member to the Containers, Documents, and Errors collections.
An alternative to the Close method is to set the value of an object variable to Nothing
(Set dbsTemp = Nothing).
Example (DAO)
This example uses the Close method on both Recordset and Database objects that have been
opened. It also demonstrates how closing a Recordset will cause unsaved changes to be lost.
Sub CloseX()
Dim dbsNorthwind As Database
Dim rstEmployees As Recordset
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
Set rstEmployees = dbsNorthwind.OpenRecordset("Employees")
' Make changes to a record but close the recordset before saving the changes.
With rstEmployees
Debug.Print "Original data"
Debug.Print " Name - Extension"
Debug.Print " " & !FirstName & " " & _
!LastName & " - " & !Extension
.Edit
!Extension = "9999"
.Close
End With
' Reopen Recordset to show that the data hasn't changed.
Set rstEmployees = dbsNorthwind.OpenRecordset("Employees")
With rstEmployees
Debug.Print "Data after Close"
Debug.Print " Name - Extension"
Debug.Print " " & !FirstName & " " & _
!LastName & " - " & !Extension
.Close
End With
dbsNorthwind.Close
End Sub
Example (Access)
The following example creates a Database object that points to the current database and
opens a table-type Recordset object based on a Customers table in the database. The
procedure uses the Close method on the Recordset object variable to free the memory
resources it has been using. It uses the Set statement with the Nothing keyword to free
resources used by the Database object variable.
You can also use the Close method of the Database object to close it and free memory.
The Close method of the Database object doesn't actually close the database that's open
in Microsoft Access; it only frees the resources used by the Database object variable.
Using an object's Close method and setting the object variable to Nothing are equivalent
ways to free memory.
Sub UseClose()
Dim dbs As Database, rst As Recordset
' Return reference to current database.
Set dbs = CurrentDb
' Create table-type recordset.
Set rst = dbs.OpenRecordset("Customers")
.
.
.
' Close recordset to free memory.
rst.Close
' Free memory used by object variable.
Set dbs = Nothing
End Sub
Example (Excel)
This example opens the Customer recordset of the Nwindex.mdb database, counts how many
records are available, and enters this number on Sheet1.
To create the Nwindex.mdb database, run the Microsoft Excel example for the CreateDatabase
method.
Dim db As Database, rs As Recordset
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set rs = db.OpenRecordset("Customer")
Set resultsSheet = Sheets("Sheet1")
resultsSheet.Activate
With resultsSheet.Cells(1, 1)
.Value = "Records in " & rs.Name & " table:"
.Font.Bold = True
.EntireColumn.AutoFit
End With
rs.MoveLast
resultsSheet.Cells(1, 2).Value = rs.RecordCount
rs.Close
db.Close
METHOD - CreateField
Creates a new Field object (Microsoft Jet workspaces only).
Syntax
Set field = object.CreateField (name, type, size)
Part Description
field An object variable that represents the Field object you want to create.
object An object variable that represents the Index, Relation, or TableDef object
for which you want to create the new Field object.
name Optional. A Variant (String subtype) that uniquely names the new Field
object. See the Name property for details on valid Field names.
type Optional. A constant that determines the data type of the new Field object.
See the Type property for valid data types.
size Optional. A Variant (Integer subtype) that indicates the maximum size,
in bytes, of a Field object that contains text. See the Size property for
valid size values. This argument is ignored for numeric and fixed-width fields.
Remarks
You can use the CreateField method to create a new field, as well as specify the name,
data type, and size of the field. If you omit one or more of the optional parts when you
use CreateField, you can use an appropriate assignment statement to set or reset the
corresponding property before you append the new object to a collection. After you append
the new object, you can alter some but not all of its property settings. See the individual
property topics for more details.
The type and size arguments apply only to Field objects in a TableDef object. These arguments
are ignored when a Field object is associated with an Index or Relation object.
If name refers to an object that is already a member of the collection, a run-time error
occurs when you use the Append method.
To remove a Field object from a Fields collection, use the Delete method on the collection.
You can't delete a Field object from a TableDef object's Fields collection after you create
an index that references the field.
Example
The following example creates a new table with two new fields. One of the fields is an
AutoNumber field. The procedure also makes this field the primary key in the table.
Sub NewTable()
Dim dbs As Database
Dim tdf As TableDef, fld1 As Field, fld2 As Field
Dim idx As Index, fldIndex As Field
' Return reference to current database.
Set dbs = CurrentDb
' Create new table with two fields.
Set tdf = dbs.CreateTableDef("Contacts")
Set fld1 = tdf.CreateField("ContactID", dbLong)
fld1.Attributes = fld1.Attributes + dbAutoIncrField
Set fld2 = tdf.CreateField("ContactName", dbText, 50)
' Append fields.
tdf.Fields.Append fld1
tdf.Fields.Append fld2
' Create primary key index.
Set idx = tdf.CreateIndex("PrimaryKey")
Set fldIndex = idx.CreateField("ContactID", dbLong)
' Append index fields.
idx.Fields.Append fldIndex
' Set Primary property.
idx.Primary = True
' Append index.
tdf.Indexes.Append idx
' Append TableDef object.
dbs.TableDefs.Append tdf
dbs.TableDefs.Refresh
Set dbs = Nothing
End Sub
Example (DAO)
This example uses the CreateField method to create three Fields for a new TableDef. It then
displays the properties of those Field objects that are automatically set by the CreateField
method. (Properties whose values are empty at the time of Field creation are not shown.)
Sub CreateFieldX()
Dim dbsNorthwind As Database
Dim tdfNew As TableDef
Dim fldLoop As Field
Dim prpLoop As Property
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
Set tdfNew = dbsNorthwind.CreateTableDef("NewTableDef")
' Create and append new Field objects for the new
' TableDef object.
With tdfNew
' The CreateField method will set a default Size
' for a new Field object if one is not specified.
.Fields.Append.CreateField("TextField", dbText)
.Fields.Append.CreateField("IntegerField", dbInteger)
.Fields.Append.CreateField("DateField", dbDate)
End With
dbsNorthwind.TableDefs.Append tdfNew
Debug.Print "Properties of new Fields in " & tdfNew.Name
' Enumerate Fields collection to show the properties of
' the new Field objects.
For Each fldLoop In tdfNew.Fields
Debug.Print " " & fldLoop.Name
For Each prpLoop In fldLoop.Properties
' Properties that are invalid in the context of
' TableDefs will trigger an error if an attempt
' is made to read their values.
On Error Resume Next
Debug.Print " " & prpLoop.Name & " - " & _
IIf(prpLoop = "", "[empty]", prpLoop)
On Error GoTo 0
Next prpLoop
Next fldLoop
' Delete new TableDef because this is a demonstration.
dbsNorthwind.TableDefs.Delete tdfNew.Name
dbsNorthwind.Close
End Sub
METHOD - CreateQueryDef (DAO)
Creates a new QueryDef object in a specified Connection or Database object.
Syntax
Set querydef = object.CreateQueryDef (name, sqltext)
The CreateQueryDef method syntax has these parts.
Part Description
querydef An object variable that represents the QueryDef object you want to create.
object An object variable that represents an open Connection or Database object
that will contain the new QueryDef.
name Optional. A Variant (String subtype) that uniquely names the new QueryDef.
sqltext Optional. A Variant (String subtype) that is an SQL statement defining the
QueryDef. If you omit this argument, you can define the QueryDef by setting
its SQL property before or after you append it to a collection.
Remarks
In a Microsoft Jet workspace, if you provide anything other than a zero-length string for
the name when you create a QueryDef, the resulting QueryDef object is automatically appended
to the QueryDefs collection. In an ODBCDirect workspace, QueryDef objects are always temporary.
In an ODBCDirect workspace, the sqltext argument can specify an SQL statement or a Microsoft
SQL Server stored procedure and its parameters.
If the object specified by name is already a member of the QueryDefs collection, a run-time
error occurs. You can create a temporary QueryDef by using a zero-length string for the name
argument when you execute the CreateQueryDef method. You can also accomplish this by setting
the Name property of a newly created QueryDef to a zero-length string (""). Temporary QueryDef
objects are useful if you want to repeatedly use dynamic SQL statements without having to
create any new permanent objects in the QueryDefs collection. You can't append a temporary
QueryDef to any collection because a zero-length string isn't a valid name for a permanent
QueryDef object. You can always set the Name and SQL properties of the newly created QueryDef
object and subsequently append the QueryDef to the QueryDefs collection.
To run the SQL statement in a QueryDef object, use the Execute or OpenRecordset method.
Using a QueryDef object is the preferred way to perform SQL pass-through queries with ODBC
databases.
To remove a QueryDef object from a QueryDefs collection in a Microsoft Jet database, use the
Delete method on the collection. For an ODBCDirect database, use the Close method on the
QueryDef object.
Example (DAO)
This example uses the CreateQueryDef method to create and execute both a temporary and
a permanent QueryDef. The GetrstTemp function is required for this procedure to run.
Sub CreateQueryDefX()
Dim dbsNorthwind As Database
Dim qdfTemp As QueryDef
Dim qdfNew As QueryDef
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
With dbsNorthwind
' Create temporary QueryDef.
Set qdfTemp = .CreateQueryDef("", _
"SELECT * FROM Employees")
' Open Recordset and print report.
GetrstTemp qdfTemp
' Create permanent QueryDef.
Set qdfNew = .CreateQueryDef("NewQueryDef", _
"SELECT * FROM Categories")
' Open Recordset and print report.
GetrstTemp qdfNew
' Delete new QueryDef because this is a demonstration.
.QueryDefs.Delete qdfNew.Name
.Close
End With
End Sub
Function GetrstTemp(qdfTemp As QueryDef)
Dim rstTemp As Recordset
With qdfTemp
Debug.Print .Name
Debug.Print " " & .SQL
' Open Recordset from QueryDef.
Set rstTemp = .OpenRecordset(dbOpenSnapshot)
With rstTemp
' Populate Recordset and print number of records.
.MoveLast
Debug.Print " Number of records = " & _
.RecordCount
Debug.Print
.Close
End With
End With
End Function
Example (Access)
The following example creates a new QueryDef object, then opens the query in Datasheet view:
Sub NewQuery()
Dim dbs As Database, qdf As QueryDef, strSQL As String
' Return reference to current database.
Set dbs = CurrentDb
strSQL = "SELECT * FROM Employees WHERE [HireDate] >= #1-1-93#"
' Create new query.
Set qdf = dbs.CreateQueryDef("RecentHires", strSQL)
DoCmd.OpenQuery qdf.Name
Set dbs = Nothing
End Sub
Example (Excel)
This example creates a new query based on the Customer recordset in the Nwindex.mdb
database. The query selects a snapshot of all customers in the state of Washington
and then copies it to Sheet1.
To create the Nwindex.mdb database, run the Microsoft Excel example for the
CreateDatabase method.
Dim db As Database, qDef As QueryDef, rs As Recordset
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set qDef = db.CreateQueryDef("WA Region")
qDef.SQL = "SELECT * FROM Customer WHERE [Region] = 'WA';"
Set rs = db.OpenRecordset("WA Region")
numberOfRows = Sheets("Sheet1").Cells(1, 1).CopyFromRecordset(rs)
Sheets("Sheet1").Activate
MsgBox numberOfRows & " records have been copied."
rs.Close
db.Close
METHOD - CreateWorkspace (DAO)
Creates a new Workspace object.
Syntax
Set workspace = CreateWorkspace(name, user, password, type)
The CreateWorkspace method syntax has these parts.
Part Description
workspace An object variable that represents the Workspace object you want to create.
name A String that uniquely names the new Workspace object. See the Name
property for details on valid Workspace names.
user A String that identifies the owner of the new Workspace object. See the
UserName property for more information.
password A String containing the password for the new Workspace object. The
password can be up to 14 characters long and can include any characters
except ASCII character 0 (null). See the Password property for more
information on valid passwords.
type Optional. A constant that indicates the type of workspace, as described
in Settings.
Settings
You can use the following constants for type.
Constant Description
dbUseJet Creates a Microsoft Jet workspace.
dbUseODBC Creates an ODBCDirect workspace.
Remarks
Once you use the CreateWorkspace method to create a new Workspace object, a Workspace
session is started, and you can refer to the Workspace object in your application.
Workspace objects aren't permanent, and you can't save them to disk. Once you create a
Workspace object, you can't alter any of its property settings, except for the Name
property, which you can modify before appending the Workspace object to the Workspaces
collection.
You don't have to append the new Workspace object to a collection before you can use it.
You append a newly created Workspace object only if you need to refer to it through the
Workspaces collection.
The type option determines whether the new Workspace is a Microsoft Jet or ODBCDirect
workspace. If you set type to dbUseODBC and you haven't already created any Microsoft
Jet workspaces, then the Microsoft Jet database engine will not be loaded into memory,
and all activity will occur with the ODBC data source subsequently identified in a
Connection object. If you omit type, the DefaultType property of DBEngine will determine
which type of data source the Workspace is connected to. You can have both Microsoft Jet
and ODBCDirect workspaces open at the same time.
To remove a Workspace object from the Workspaces collection, close all open databases and
connections and then use the Close method on the Workspace object.
Example
This example uses the CreateWorkspace method to create both a Microsoft Jet workspace
and an ODBCDirect workspace. It then lists the properties of both types of workspace.
Sub CreateWorkspaceX()
Dim wrkODBC As Workspace
Dim wrkJet As Workspace
Dim wrkLoop As Workspace
Dim prpLoop As Property
' Create an ODBCDirect workspace.
' Until you create the Microsoft Jet workspace, the Microsoft
' Jet database engine will not be loaded into memory.
Set wrkODBC = CreateWorkspace("ODBCWorkspace", "admin", _
"", dbUseODBC)
Workspaces.Append wrkODBC
DefaultType = dbUseJet
' Create an unnamed Workspace object of the type
' specified by the DefaultType property of DBEngine
' (dbUseJet).
Set wrkJet = CreateWorkspace("", "admin", "")
' Enumerate Workspaces collection.
Debug.Print "Workspace objects in Workspaces collection:"
For Each wrkLoop In Workspaces
Debug.Print " " & wrkLoop.Name
Next wrkLoop
With wrkODBC
' Enumerate Properties collection of ODBCDirect
' workspace.
Debug.Print "Properties of " & .Name
On Error Resume Next
For Each prpLoop In .Properties
Debug.Print " " & prpLoop.Name & " = " & prpLoop
Next prpLoop
On Error GoTo 0
End With
With wrkJet
' Enumerate Properties collection of Microsoft Jet
' workspace.
Debug.Print "Properties of unnamed Microsoft Jet workspace"
On Error Resume Next
For Each prpLoop In .Properties
Debug.Print " " & prpLoop.Name & " = " & prpLoop
Next prpLoop
On Error GoTo 0
End With
wrkODBC.Close
wrkJet.Close
End Sub
METHOD - DoMenuItem
The DoMenuItem method carries out the DoMenuItem action in Visual Basic. For more
information on how the action and its arguments work, see the action topic.
Note
In Microsoft Access 97, the DoMenuItem method has been replaced by the RunCommand
method. The DoMenuItem method is included in this version of Microsoft Access only for
compatibility with previous versions. When you run existing Visual Basic code containing
a DoMenuItem method, Microsoft Access will display the appropriate menu or toolbar command
for Microsoft Access 97. However, unlike the DoMenuItem action in a macro, a DoMenuItem
method in Visual Basic code isn't converted to a RunCommand method when you convert a
database created in a previous version of Microsoft Access.
Some commands from previous versions of Microsoft Access aren't available in Microsoft
Access 97, and DoMenuItem methods that run these commands will cause an error when they're
executed in Visual Basic. You must edit your Visual Basic code to replace or delete
occurrences of such DoMenuItem methods. For a list of these commands, see DoMenuItem
Action Commands Not Available with the RunCommand Action.
Syntax
DoCmd.DoMenuItem menubar, menuname, command[, subcommand][, version]
Argument Description
menubar Use the intrinsic constant acFormBar for the menu bar in Form view.
For other views, use the number of the view in the Menu Bar argument list,
as shown in the Macro window in previous versions of Microsoft Access
(count down the list, starting from 0).
menuname You can use one of the following intrinsic constants:
acFile
acEditMenu
acRecordsMenu
You can use acRecordsMenu only for the Form view menu bar in Microsoft
Access version 2.0 and Microsoft Access 95 databases.
For other menus, use the number of the menu in the Menu Name argument list,
as shown in the Macro window in previous versions of Microsoft Access
(count down the list, starting from 0).
command You can use one of the following intrinsic constants:
acNew
acSaveForm
acSaveFormAs
acSaveRecord
acUndo
acCut
acCopy
acPaste
acDelete
acSelectRecord
acSelectAllRecords
acObject
acRefresh
For other commands, use the number of the command in the Command argument list,
as shown in the Macro window in previous versions of Microsoft Access (count down
the list, starting from 0).
subcommand You can use one of the following intrinsic constants:
acObjectVerb
acObjectUpdate
The acObjectVerb constant represents the first command on the submenu of
the Object command on the Edit menu. The type of object determines the first
command on the submenu. For example, this command is Edit for a Paintbrush
object that can be edited.
For other commands on submenus, use the number of the subcommand in the
Subcommand argument list, as shown in the Macro window in previous versions
of Microsoft Access (count down the list, starting from 0).
version Use the intrinsic constant acMenuVer70 for code written for Microsoft
Access 95 databases, the intrinsic constant acMenuVer20 for code written
for Microsoft Access version 2.0 databases, and the intrinsic constant
acMenuVer1X for code written for Microsoft Access version 1.x databases.
This argument is available only in Visual Basic.
Note
The default for this argument is acMenuVer1X, so that any code written for
Microsoft Access version 1.x databases will run unchanged. If you're writing
code for a Microsoft Access 95 or version 2.0 database and want to use the
Microsoft Access 95 or version 2.0 menu commands with the DoMenuItem method,
you must set this argument to acMenuVer70 or acMenuVer20.
Also, when you are counting down the lists for the Menu Bar, Menu Name,
Command, and Subcommand action arguments in the Macro window to get the
numbers to use for the arguments in the DoMenuItem method, you must use the
Microsoft Access 95 lists if the version argument is acMenuVer70, the
Microsoft Access version 2.0 lists if the version argument is acMenuVer20,
and the Microsoft Access version 1.x lists if version is acMenuVer1X (or blank).
Note
There is no acMenuVer80 setting for this argument. You can't use the
DoMenuItem method to display Microsoft Access 97 commands (although
existing DoMenuItem methods in Visual Basic code will still work). Use
the RunCommand method instead.
Remarks
The selections in the lists for the Menu Name, Command, and Subcommand action arguments
in the Macro window depend on what you've selected for the previous arguments. You must
use numbers or intrinsic constants that are appropriate for each menubar, menuname,
command, and subcommand argument.
If you leave the subcommand argument blank but specify the version argument, you must
include the subcommand argument's comma. If you leave the subcommand and version arguments
blank, don't use a comma following the command argument.
METHOD - FindNext
The FindNext method carries out the FindNext action in Visual Basic. For more information
on how the action works, see the action topic.
Syntax
DoCmd.FindNext
This method has no arguments.
METHOD - FindRecord
Applies to DoCmd Object
The FindRecord method carries out the FindRecord action in Visual Basic. For more
information on how the action and its arguments work, see the action topic.
Syntax
DoCmd.FindRecord findwhat[, match][, matchcase][, search][, searchasformatted][,
onlycurrentfield][, findfirst]
The FindRecord method has the following arguments.
Argument Description
findwhat An expression that evaluates to text, a number, or a date. The
expression contains the data to search for.
match One of the following intrinsic constants:
acAnywhere
acEntire (default)
acStart
If you leave this argument blank, the default constant
(acEntire) is assumed.
matchcase Use True (–1) for a case-sensitive search and False (0) for a
search that's not case-sensitive. If you leave this argument
blank, the default (False) is assumed.
search One of the following intrinsic constants:
acDown
acSearchAll (default)
acUp
If you leave this argument blank, the default constant
(acSearchAll) is assumed.
searchasformatted Use True to search for data as it's formatted and False to search
for data as it's stored in the database.
If you leave this argument blank, the default (False) is assumed.
onlycurrentfield One of the following intrinsic constants:
acAll
acCurrent (default)
If you leave this argument blank, the default constant
(acCurrent) is assumed.
findfirst Use True to start the search at the first record. Use False to
start the search at the record following the current record. If
you leave this argument blank, the default (True) is assumed.
Remarks
You can leave an optional argument blank in the middle of the syntax, but you must include
the argument's comma. If you leave one or more trailing arguments blank, don't use a comma
following the last argument you specify.
Example
The following example finds the first occurrence in the records of the name Smith in the
current field. It doesn't find occurrences of smith or Smithson.
DoCmd.FindRecord "Smith",, True,, True
METHOD - Item
Returns a specific member of a Collection object either by position or by key.
Syntax
object.Item(index)
The Item method syntax has the following object qualifier and part:
Part Description
object Required. An object expression that evaluates to an object in the Applies To list.
index Required. An expression that specifies the position of a member of the collection.
If a numeric expression, index must be a number from 1 to the value of the
collection's Count property. If a string expression, index must correspond to the
key argument specified when the member referred to was added to the collection.
Remarks
If the value provided as index doesn’t match any existing member of the collection, an
error occurs.
The Item method is the default method for a collection. Therefore, the following lines
of code are equivalent:
Print MyCollection(1)
Print MyCollection.Item(1)
METHOD - NewCurrentDatabase
You can use the NewCurrentDatabase method to create a new database in the Microsoft Access
window. You can use this method to create a new database from another application that is
controlling Microsoft Access through Automation, formerly called OLE Automation. For example,
you can use the NewCurrentDatabase method from Microsoft Excel to create a new database in the
Microsoft Access window.
Syntax
application.NewCurrentDatabase dbname
Argument Description
application The Application object.
dbname A string expression that is the name of a new database file, including
the path name and the file name extension. If your network supports it,
you can also specify a network path in the following form:
\\Server\Share\Folder\Filename.mdb
Remarks
The NewCurrentDatabase method enables you to create a new Microsoft Access database from
another application through Automation. Once you have created an instance of Microsoft
Access from another application, you must also create a new database. This database opens
in the Microsoft Access window.
If the database identified by dbname already exists, an error occurs.
The new database is opened under the Admin user account.
Example
The following example creates a new Microsoft Access database from another application
through Automation, and then creates a new table in that database.
You can enter this code in a Visual Basic module in any application that can act as an
ActiveX component. For example, you might run the following code from Microsoft Excel,
Microsoft Visual Basic, or even Microsoft Access.
When the variable pointing to the Application object goes out of scope, the instance of
Microsoft Access that it represents closes as well. Therefore, you should declare this
variable at the module level.
' Include following in Declarations section of module.
Dim appAccess As Access.Application
Sub NewAccessDatabase()
Dim dbs As Database, tdf As TableDef, fld As Field
Dim strDB As String
' Initialize string to database path.
strDB = "C:\My Documents\Newdb.mdb"
' Create new instance of Microsoft Access.
Set appAccess = _
CreateObject("Access.Application.8")
' Open database in Microsoft Access window.
appAccess.NewCurrentDatabase strDB
' Get Database object variable.
Set dbs = appAccess.CurrentDb
' Create new table.
Set tdf = dbs.CreateTableDef("Contacts")
' Create field in new table.
Set fld = tdf. _
CreateField("CompanyName", dbText, 40)
' Append Field and TableDef objects.
tdf.Fields.Append fld
dbs.TableDefs.Append tdf
Set appAccess = Nothing
End Sub
Note
From some applications, such as Microsoft Visual Basic, you can include the New keyword
when declaring the Application object variable. This keyword automatically creates a new
instance of Microsoft Access, without requiring you to use the CreateObject function.
Check your application's documentation to determine whether it supports this syntax.
METHOD - OpenDatabase
Opens a specified database in a Workspace Object and returns a reference to the Database
object that represents it.
Syntax
Set database = workspace.OpenDatabase (dbname, options, read-only, connect)
The OpenDatabase method syntax has these parts.
Part Description
database An object variable that represents the Database object that you want to open.
workspace Optional. An object variable that represents the existing Workspace object
that will contain the database. If you don't include a value for workspace,
OpenDatabase uses the default workspace.
dbname A String that is the name of an existing Microsoft Jet database file, or the
data source name (DSN) of an ODBC data source. See the Name property for more
information about setting this value.
options Optional. A Variant that sets various options for the database, as specified
in Settings.
read-only Optional. A Variant (Boolean subtype) value that is True if you want to open
the database with read-only access, or False (default) if you want to open
the database with read/write access.
connect Optional. A Variant (String subtype) that specifies various connection
information, including passwords.
Settings
For Microsoft Jet workspaces, you can use the following values for the options argument.
Setting Description
True Opens the database in exclusive mode.
False (Default) Opens the database in shared mode.
For ODBCDirect workspaces, the options argument determines if and when to prompt the user
to establish the connection. You can use one of the following constants.
Constant Description
dbDriverNoPrompt The ODBC Driver Manager uses the connection string provided
in dbname and connect. If you don't provide sufficient
information, a run-time error occurs.
dbDriverPrompt The ODBC Driver Manager displays the ODBC Data Sources
dialog box, which displays any relevant information supplied
in dbname or connect. The connection string is made up of the
DSN that the user selects via the dialog boxes, or, if the
user doesn't specify a DSN, the default DSN is used.
dbDriverComplete (Default) If the connect and dbname arguments include all
the necessary information to complete a connection, the ODBC
Driver Manager uses the string in connect. Otherwise it
behaves as it does when you specify dbDriverPrompt.
dbDriverCompleteRequired This option behaves like dbDriverComplete except the ODBC
driver disables the prompts for any information not required
to complete the connection.
Remarks
When you open a database, it is automatically added to the Databases collection. Further,
in an ODBCDirect workspace, the Connection object corresponding to the new Database object
is also created and appended to the Connections collection of the same Workspace object.
Some considerations apply when you use dbname:
· If it refers to a database that is already open for exclusive access by another user, an
error occurs.
· If it doesn't refer to an existing database or valid ODBC data source name, an error occurs.
· If it's a zero-length string ("") and connect is "ODBC;", a dialog box listing all
registered ODBC data source names is displayed so the user can select a database.
· If you're opening a database through an ODBCDirect workspace and you provide the DSN in
connect, you can set dbname to a string of your choice that you can use to reference
this database in subsequent code.
The connect argument is expressed in two parts: the database type, followed by a
semicolon (;) and the optional arguments. You must first provide the database type,
micolons. One of the parameters may be the password (if one is assigned).
For example:
"FoxPro 2.5; pwd=mypassword"
Using the NewPassword method on a Database object other than an ODBCDirect database changes
the password parameter that appears in the ";pwd=..." part of this argument. You must supply
the options and read-only arguments to supply a source string. See the Connect property for
syntax.
To close a database, and thus remove the Database object from the Databases collection, use
the Close method on the object.
Note
When you access a Microsoft Jet-connected ODBC data source, you can improve your
application's performance by opening a Database object connected to the ODBC data
source, rather than by linking individual TableDef objects to specific tables in
the ODBC data source.
Example (DAO)
This example uses the OpenDatabase method to open one Microsoft Jet database and two
Microsoft Jet-connected ODBC databases.
Sub OpenDatabaseX()
Dim wrkJet As Workspace
Dim dbsNorthwind As Database
Dim dbsPubs As Database
Dim dbsPubs2 As Database
Dim dbsLoop As Database
Dim prpLoop As Property
' Create Microsoft Jet Workspace object.
Set wrkJet = CreateWorkspace("", "admin", "", dbUseJet)
' Open Database object from saved Microsoft Jet database
' for exclusive use.
MsgBox "Opening Northwind..."
Set dbsNorthwind = wrkJet.OpenDatabase("Northwind.mdb", True)
' Open read-only Database object based on information in
' the connect string.
MsgBox "Opening pubs..."
Set dbsPubs = wrkJet.OpenDatabase("Publishers", _
dbDriverNoPrompt, True, _
"ODBC;DATABASE=pubs;UID=sa;PWD=;DSN=Publishers")
' Open read-only Database object by entering only the
' missing information in the ODBC Driver Manager dialog
' box.
MsgBox "Opening second copy of pubs..."
Set dbsPubs2 = wrkJet.OpenDatabase("Publishers", _
dbDriverCompleteRequired, True, _
"ODBC;DATABASE=pubs;DSN=Publishers;")
' Enumerate the Databases collection.
For Each dbsLoop In wrkJet.Databases
Debug.Print "Database properties for " & _
dbsLoop.Name & ":"
On Error Resume Next
' Enumerate the Properties collection of each Database object.
For Each prpLoop In dbsLoop.Properties
If prpLoop.Name = "Connection" Then
' Property actually returns a Connection object.
Debug.Print " Connection[.Name] = " & _
dbsLoop.Connection.Name
Else
Debug.Print " " & prpLoop.Name & " = " & _
prpLoop
End If
Next prpLoop
On Error GoTo 0
Next dbsLoop
dbsNorthwind.Close
dbsPubs.Close
dbsPubs2.Close
wrkJet.Close
End Sub
Example (Access)
The following example returns a Database variable that points to the current database.
Then it opens a different database called Another.mdb by using the OpenDatabase method.
The procedure then enumerates all TableDef objects in both databases.
To try this example, create a new database called Another.mdb, close it, and place it in
the same directory as the database from which you are running the code.
Sub OpenAnother()
Dim wsp As Workspace
Dim dbs As Database, dbsAnother As Database
Dim tdf As TableDef
' Return reference to current database.
Set dbs = CurrentDb
' Return reference to default workspace.
Set wsp = DBEngine.Workspaces(0)
' Return reference to Another.mdb.
Set dbsAnother = wsp.OpenDatabase("Another.mdb")
' Enumerate all TableDef objects in each database.
Debug.Print dbs.Name & ":"
For Each tdf in dbs.TableDefs
Debug.Print tdf.Name
Next tdf
Debug.Print
Debug.Print dbsAnother.Name & ":"
For Each tdf in dbsAnother.TableDefs
Debug.Print tdf.Name
Next tdf
Set dbs = Nothing
Set dbsAnother = Nothing
End Sub
Example (Excel)
This example displays a custom dialog box that contains a list of all the databases with
the file name extension .mdb that are located in the Microsoft Excel folder, and then it
opens the database selected by the user.
Dim a(100), db As Database
i = 0
ChDrive "C"
ChDir Application.Path
a(i) = Dir("*.MDB")
If a(i) = "" Then
MsgBox "You have no databases in the Microsoft Excel folder"
Exit Sub
End If
Do
i = i + 1
a(i) = Dir()
Loop Until a(i) = ""
Set theDialog = DialogSheets.Add
Set list1 = theDialog.ListBoxes.Add(78, 42, 84, 80)
For counter = 0 To i - 1
list1.AddItem a(counter)
Next
Application.ScreenUpdating = True
theDialog.Show
Set db = Workspaces(0).OpenDatabase(a(list1.Value - 1))
MsgBox "The " & db.Name & " database is now open"
' use database here
db.Close
METHOD - OpenForm
The OpenForm method carries out the OpenForm action in Visual Basic. For more information
on how the action and its arguments work, see the action topic.
Syntax
DoCmd.OpenForm formname[, view][, filtername][, wherecondition][, datamode][, windowmode]
[, openargs]
The OpenForm method has the following arguments.
Argument Description
formname A string expression that's the valid name of a form in the current database.
If you execute Visual Basic code containing the OpenForm method in a library
database, Microsoft Access looks for the form with this name first in the
library database, then in the current database.
view One of the following intrinsic constants:
acDesign
acFormDS
acNormal (default)
acPreview
acNormal opens the form in Form view.
If you leave this argument blank, the default constant (acNormal) is assumed.
filtername A string expression that's the valid name of a query in the current database.
wherecondition A string expression that's a valid SQL WHERE clause without the word WHERE.
datamode One of the following intrinsic constants:
acFormAdd
acFormEdit
acFormPropertySettings (default)
acFormReadOnly
If you leave this argument blank (the default constant, acFormPropertySettings,
is assumed), Microsoft Access opens the form in the data mode set by the
form's AllowEdits, AllowDeletions, AllowAdditions, and DataEntry properties.
windowmode One of the following intrinsic constants:
acDialog
acHidden
acIcon
acWindowNormal (default)
If you leave this argument blank, the default constant (acWindowNormal)
is assumed.
openargs A string expression. This expression is used to set the form's OpenArgs
property. This setting can then be used by code in a form module, such as
the Open event procedure. The OpenArgs property can also be referred to in
macros and expressions.
For example, suppose that the form you open is a continuous-form list of
clients. If you want the focus to move to a specific client record when
the form opens, you can specify the client name with the openargs argument,
and then use the FindRecord method to move the focus to the record for the
client with the specified name.
This argument is available only in Visual Basic.
Remarks
The maximum length of the wherecondition argument is 32,768 characters (unlike the Where
Condition action argument in the Macro window, whose maximum length is 256 characters).
You can leave an optional argument blank in the middle of the syntax, but you must include
the argument's comma. If you leave a trailing argument blank, don't use a comma following
the last argument you specify.
METHOD - OpenQuery
The OpenQuery method carries out the OpenQuery action in Visual Basic. For more information
on how the action and its arguments work, see the action topic.
Syntax
DoCmd.OpenQuery queryname[, view][, datamode]
The OpenQuery method has the following arguments.
Argument Description
queryname A string expression that's the valid name of a query in the current
database.
If you execute Visual Basic code containing the OpenQuery method in a
library database, Microsoft Access looks for the query with this name
first in the library database, then in the current database.
view One of the following intrinsic constants:
acViewDesign
acViewNormal (default)
acViewPreview
If the queryname argument is the name of a select, crosstab, union, or
pass-through query whose ReturnsRecords property is set to –1, acViewNormal
displays the query's result set. If the queryname argument refers to an
action, data-definition, or pass-through query whose ReturnsRecords property
is set to 0, acViewNormal runs the query.
If you leave this argument blank, the default is acViewNormal.
datamode One of the following intrinsic constants:
acAdd
acEdit (default)
acReadOnly
If you leave this argument blank, the default is acEdit.
Remarks
If you specify the datamode argument and leave the view argument blank, you must include
the view argument's comma. If you leave a trailing argument blank, don't use a comma
following the last argument you specify.
Example
The following example opens Sales Totals Query in Datasheet view and enables the user to
view but not to edit or add records:
DoCmd.OpenQuery "Sales Totals Query", , acReadOnly
METHOD - OpenRecordset
Creates a new Recordset object and appends it to the Recordsets collection.
Syntax
For Connection and Database objects:
Set recordset = object.OpenRecordset (source, type, options, lockedits)
For QueryDef, Recordset, and TableDef objects:
Set recordset = object.OpenRecordset (type, options, lockedits)
The OpenRecordset method syntax has these parts.
Part Description
recordset An object variable that represents the Recordset object you want to open.
object An object variable that represents an existing object from which you want
to create the new Recordset.
source A String specifying the source of the records for the new Recordset. The
source can be a table name, a query name, or an SQL statement that returns
records. For table-type Recordset objects in Microsoft Jet databases, the
source can only be a table name.
type Optional. A constant that indicates the type of Recordset to open, as
specified in Settings.
options Optional. A combination of constants that specify characteristics of the
new Recordset, as listed in Settings.
lockedits Optional. A constant that determines the locking for the Recordset, as
specified in Settings.
Settings
You can use one of the following constants for the type argument.
Constant Description
dbOpenTable Opens a table-type Recordset object (Microsoft Jet workspaces
only) [Jet Default, if possible].
dbOpenDynamic Opens a dynamic-type Recordset object, which is similar to an ODBC
dynamic cursor. (ODBCDirect workspaces only)
dbOpenDynaset Opens a dynaset-type Recordset object, which is similar to an ODBC
keyset cursor [linked table or query Default].
dbOpenSnapshot Opens a snapshot-type Recordset object, which is similar to an ODBC
static cursor.
dbOpenForwardOnly Opens a forward-only-type Recordset object [ODBCDirect workspace
Default].
Note
If you open a Recordset in a Microsoft Jet workspace and you don't specify a type,
OpenRecordset creates a table-type Recordset, if possible. If you specify a linked
table or query, OpenRecordset creates a dynaset-type Recordset. In an ODBCDirect
workspace, the default setting is dbOpenForwardOnly.
You can use a combination of the following constants for the options argument.
Constant Description
dbAppendOnly Allows users to append new records to the Recordset, but prevents
them from editing or deleting existing records (Microsoft Jet
dynaset-type Recordset only).
dbSQLPassThrough Passes an SQL statement to a Microsoft Jet-connected ODBC data
source for processing (Microsoft Jet snapshot-type Recordset only).
dbSeeChanges Generates a run-time error if one user is changing data that another
user is editing (Microsoft Jet dynaset-type Recordset only). This
is useful in applications where multiple users have simultaneous
read/write access to the same data.
dbDenyWrite Prevents other users from modifying or adding records (Microsoft
Jet Recordset objects only).
dbDenyRead Prevents other users from reading data in a table (Microsoft Jet
table-type Recordset only).
dbForwardOnly Creates a forward-only Recordset (Microsoft Jet snapshot-type
Recordset only). It is provided only for backward compatibility,
and you should use the dbOpenForwardOnly constant in the type
argument instead of using this option.
dbReadOnly Prevents users from making changes to the Recordset (Microsoft Jet
only). The dbReadOnly constant in the lockedits argument replaces
this option, which is provided only for backward compatibility.
dbRunAsync Runs an asynchronous query (ODBCDirect workspaces only).
dbExecDirect Runs a query by skipping SQLPrepare and directly calling
SQLExecDirect (ODBCDirect workspaces only). Use this option only
when you’re not opening a Recordset based on a parameter query.
For more information, see the "Microsoft ODBC 3.0 Programmer’s
Reference."
dbInconsistent Allows inconsistent updates (Microsoft Jet dynaset-type and
snapshot-type Recordset objects only).
dbConsistent Allows only consistent updates (Microsoft Jet dynaset-type and
snapshot-type Recordset objects only).
Note
The constants dbConsistent and dbInconsistent are mutually exclusive, and using both
causes an error. Supplying a lockedits argument when options uses the dbReadOnly constant
also causes an error.
You can use the following constants for the lockedits argument.
Constant Description
dbReadOnly Prevents users from making changes to the Recordset (default for
ODBCDirect workspaces). You can use dbReadOnly in either the options
argument or the lockedits argument, but not both. If you use it for
both arguments, a run-time error occurs.
dbPessimistic Uses pessimistic locking to determine how changes are made to the
Recordset in a multiuser environment. The page containing the record
you're editing is locked as soon as you use the Edit method (default
for Microsoft Jet workspaces).
dbOptimistic Uses optimistic locking to determine how changes are made to the
Recordset in a multiuser environment. The page containing the record
is not locked until the Update method is executed.
dbOptimisticValue Uses optimistic concurrency based on row values (ODBCDirect workspaces
only).
dbOptimisticBatch Enables batch optimistic updating (ODBCDirect workspaces only).
Remarks
In a Microsoft Jet workspace, if object refers to a QueryDef object, or a dynaset- or
snapshot-type Recordset, or if source refers to an SQL statement or a TableDef that
represents a linked table, you can't use dbOpenTable for the type argument; if you do,
a run-time error occurs. If you want to use an SQL pass-through query on a linked table
in a Jet-connected ODBC data source, you must first set the Connect property
of the linked table's database to a valid ODBC connection string. If you only need to
make a single pass through a Recordset opened from a Microsoft Jet-connected ODBC data
source, you can improve performance by using dbOpenForwardOnly for the type argument.
If object refers to a dynaset- or snapshot-type Recordset, the new Recordset is of the
same type object. If object refers to a table-type Recordset object, the type of the new
object is a dynaset-type Recordset. You can't open new Recordset objects from
forward-only–type or ODBCDirect Recordset objects.
In an ODBCDirect workspace, you can open a Recordset containing more than one select query
in the source argument, such as
"SELECT LastName, FirstName FROM Authors
WHERE LastName = 'Smith';
SELECT Title, ISBN FROM Titles
WHERE ISBN Like '1-55615-*'"
The returned Recordset will open with the results of the first query. To obtain the result
sets of records from subsequent queries, use the NextRecordset method.
Note
You can send DAO queries to a variety of different database servers with ODBCDirect,
and different servers will recognize slightly different dialects of SQL. Therefore,
context-sensitive Help is no longer provided for Microsoft Jet SQL, although online Help for
Microsoft Jet SQL is still included through the Help menu. Be sure to check the appropriate
reference documentation for the SQL dialect of your database server when using either
ODBCDirect connections or pass-through queries in Microsoft Jet-connected client/server
applications.
Use the dbSeeChanges constant in a Microsoft Jet workspace if you want to trap changes while
two or more users are editing or deleting the same record. For example, if two users start
editing the same record, the first user to execute the Update method succeeds. When the second
user invokes the Update method, a run-time error occurs. Similarly, if the second user tries
to use the Delete method to delete the record, and the first user has already changed it, a
run-time error occurs.
Typically, if the user gets this error while updating a record, your code should refresh
the contents of the fields and retrieve the newly modified values. If the error occurs while
deleting a record, your code could display the new record data to the user and a message
indicating that the data has recently changed. At this point, your code can request a
confirmation that the user still wants to delete the record.
You should also use the dbSeeChanges constant if you open a Recordset in a Microsoft
Jet-connected ODBC workspace against a Microsoft SQL Server 6.0 (or later) table that
has an IDENTITY column, otherwise an error may result.
In an ODBCDirect workspace, you can execute asynchronous queries by setting the dbRunAsync
constant in the options argument. This allows your application to continue processing other
statements while the query runs in the background. But, you cannot access the Recordset data
until the query has completed. To determine whether the query has finished executing, check
the StillExecuting property of the new Recordset. If the query takes longer to complete than
you anticipated, you can terminate execution of the query with the Cancel method.
Opening more than one Recordset on an ODBC data source may fail because the connection is
busy with a prior OpenRecordset call. One way around this is to use a server-side cursor
and ODBCDirect, if the server supports this; or fully populate the Recordset by using
the MoveLast method as soon as the Recordset is opened.
If you open a Connection object with DefaultCursorDriver set to dbUseClientBatchCursor, you
can open a Recordset to cache changes to the data (known as batch updating) in an ODBCDirect
workspace. Include dbOptimisticBatch in the lockedits argument to enable update caching. See
the Update method topic for details about how to write changes to disk immediately, or to
cache changes and write them to disk as a batch.
Closing a Recordset with the Close method automatically deletes it from the Recordsets
collection.
Note
If source refers to an SQL statement composed of a string concatenated with a non-integer
value, and the system parameters specify a non-U.S. decimal character such as a comma
(for example, strSQL = "PRICE > " & lngPrice, and lngPrice = 125,50), an error occurs when
you try to open the Recordset
This is because during concatenation, the number will be converted to a string using your
system's default decimal character, and SQL only accepts U.S. decimal characters.
Example
The following example opens a dynaset-type Recordset object and prints the number of
records in the Recordset object.
Sub UKOrders()
Dim dbs As Database, rst As Recordset
Dim strSQL As String
' Return reference to current database.
Set dbs = CurrentDb
strSQL = "SELECT * FROM Orders WHERE [ShipCountry] = 'UK'"
Set rst = dbs.OpenRecordset(strSQL)
rst.MoveLast
Debug.Print rst.RecordCount
rst.Close
Set dbs = Nothing
End Sub
METHOD - OpenTable
The OpenTable method carries out the OpenTable action in Visual Basic. For more information on how the action and its arguments work, see the action topic.
Applies to
DoCmd Object
Syntax
DoCmd.OpenTable tablename[, view][, datamode]
The OpenTable method has the following arguments.
Argument Description
tablename A string expression that's the valid name of a table in the current
database.
If you execute Visual Basic code containing the OpenTable method in a
library database, Microsoft Access looks for the table with this name
first in the library database, then in the current database.
view One of the following intrinsic constants:
acViewDesign
acViewNormal (default)
acViewPreview
acViewNormal opens the table in Datasheet view.
datamode One of the following intrinsic constants:
acAdd
acEdit (default)
acReadOnly
Remarks
If you specify the datamode argument and leave the view argument blank, you must include
the view argument's comma. If you leave a trailing argument blank, don't use a comma
following the last argument you specify
Example
The following example opens the Employees table in Print Preview:
DoCmd.OpenTable "Employees", acViewPreview
METHOD - Requery
Updates the data in a Recordset object by re-executing the query on which the object
is based.
Syntax
recordset.Requery newquerydef
The Requery method syntax has the following parts.
Part Description
recordset An object variable that represents an existing Microsoft Jet dynaset-,
snapshot-, or forward-only–type Recordset object, or an ODBCDirect
Recordset object.
newquerydef Optional. A Variant that represents the Name property value of a QueryDef
object (Microsoft Jet workspaces only).
Remarks
Use this method to make sure that a Recordset contains the most recent data. This method
re-populates the current Recordset by using either the current query parameters or (in a
Microsoft Jet workspace) the new ones supplied by the newquerydef argument.
In an ODBCDirect workspace, if the original query was asynchronous, then Requery will also
execute an asynchronous query.
If you don't specify a newquerydef argument, the Recordset is re-populated based on the
same query definition and parameters used to originally populate the Recordset. Any changes
to the underlying data will be reflected during this re-population. If you didn't use a
QueryDef to create the Recordset, the Recordset is re-created from scratch.
If you specify the original QueryDef in the newquerydef argument, then the Recordset is
requeried using the parameters specified by the QueryDef. Any changes to the underlying
data will be reflected during this re-population. To reflect any changes to the query
parameter values in the Recordset, you must supply the newquerydef argument.
If you specify a different QueryDef than what was originally used to create the Recordset,
the Recordset is re-created from scratch.
When you use Requery, the first record in the Recordset becomes the current record.
You can't use the Requery method on dynaset- or snapshot-type Recordset objects whose
Restartable property is set to False. However, if you supply the optional newquerydef
argument, the Restartable property is ignored.
If both the BOF and EOF property settings of the Recordset object are True after you use
the Requery method, the query didn't return any records and the Recordset contains no data.
Example
This example shows how the Requery method can be used to refresh a query after underlying
data has been changed.
Sub RequeryX()
Dim dbsNorthwind As Database
Dim qdfTemp As QueryDef
Dim rstView As Recordset
Dim rstChange As Recordset
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
Set qdfTemp = dbsNorthwind.CreateQueryDef("", _
"PARAMETERS ViewCountry Text; " & _
"SELECT FirstName, LastName, Country FROM " & _
"Employees WHERE Country = [ViewCountry] " & _
"ORDER BY LastName")
qdfTemp.Parameters!ViewCountry = "USA"
Debug.Print "Data after initial query, " & _
[ViewCountry] = USA"
Set rstView = qdfTemp.OpenRecordset
Do While Not rstView.EOF
Debug.Print " " & rstView!FirstName & " " & _
rstView!LastName & ", " & rstView!Country
rstView.MoveNext
Loop
' Change underlying data.
Set rstChange = dbsNorthwind.OpenRecordset("Employees")
rstChange.AddNew
rstChange!FirstName = "Nina"
rstChange!LastName = "Roberts"
rstChange!Country = "USA"
rstChange.Update
rstView.Requery
Debug.Print "Requery after changing underlying data"
Set rstView = qdfTemp.OpenRecordset
Do While Not rstView.EOF
Debug.Print " " & rstView!FirstName & " " & _
rstView!LastName & ", " & rstView!Country
rstView.MoveNext
Loop
' Restore original data because this is only a demonstration.
rstChange.Bookmark = rstChange.LastModified
rstChange.Delete
rstChange.Close
rstView.Close
dbsNorthwind.Close
End Sub
This example shows how the Requery method can be used to refresh a query after the query
parameters have been changed.
Sub RequeryX2()
Dim dbsNorthwind As Database
Dim qdfTemp As QueryDef
Dim prmCountry As Parameter
Dim rstView As Recordset
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
Set qdfTemp = dbsNorthwind.CreateQueryDef("", _
"PARAMETERS ViewCountry Text; " & _
"SELECT FirstName, LastName, Country FROM " & _
"Employees WHERE Country = [ViewCountry] " & _
"ORDER BY LastName")
Set prmCountry = qdfTemp.Parameters!ViewCountry
qdfTemp.Parameters!ViewCountry = "USA"
Debug.Print "Data after initial query, " & [ViewCountry] = USA"
Set rstView = qdfTemp.OpenRecordset
Do While Not rstView.EOF
Debug.Print " " & rstView!FirstName & " " & _
rstView!LastName & ", " & rstView!Country
rstView.MoveNext
Loop
' Change query parameter.
qdfTemp.Parameters!ViewCountry = "UK"
' QueryDef argument must be included so that the resulting Recordset
' reflects the change in the query parameter.
rstView.Requery qdfTemp
Debug.Print "Requery after changing parameter, " & _
"[ViewCountry] = UK"
Do While Not rstView.EOF
Debug.Print " " & rstView!FirstName & " " & _
rstView!LastName & ", " & rstView!Country
rstView.MoveNext
Loop
rstView.Close
dbsNorthwind.Close
End Sub
METHOD - Remove
Removes a member from a Collection object.
Syntax
object.Remove index
The Remove method syntax has the following object qualifier and part:
Part Description
object Required. An object expression that evaluates to an object in the
Applies To list.
index Required. An expression that specifies the position of a member of the collection.
If a numeric expression, index must be a number from 1 to the value of the
collection's Count property. If a string expression, index must correspond to the
key argument specified when the member referred to was added to the collection.
Remarks
If the value provided as index doesn’t match an existing member of the collection,
an error occurs.
Example
The example verifies that a particular member of the VBComponents collection is a module,
and then it uses the Remove method to remove the module.
Debug.Print Application.VBE.ActiveVBProject.VBComponents(4).Name
Application.VBE.ActiveVBProject.VBComponents.Remove Application.VBE.ActiveVBProject.VBComponents(4)
Example
This example illustrates the use of the Remove method to remove objects from a
Collection object, MyClasses. This code removes the object whose index is 1 on each
iteration of the loop.
Dim Num, MyClasses
' Remove the first object each time through the loop until
' there areno objects left in the collection.
For Num = 1 To MyClasses.Count
MyClasses.Remove 1
Next Num
METHOD - Run
You can use the Run method to carry out a specified Microsoft Access or user-defined
Function or Sub procedure. This method is useful when you are controlling Microsoft
Access from another application through Automation, formerly called OLE Automation.
For example, you can use the Run method from an ActiveX component to carry out a Sub
procedure that is defined within a Microsoft Access database.
Syntax
application.Run procedure[, arg1, arg2, ..., arg30]
Argument Description
application The Application object.
procedure The name of the Function or Sub procedure to be run. If you are calling
a procedure in another database use the project name and the procedure name
separated by a dot in the form:
"projectname.procedurename"
If you execute Visual Basic code containing the Run method in a library
database, Microsoft Access looks for the procedure first in the library
database, then in the current database.
arg1, arg2,.. Optional. The arguments for the specified Function or Sub procedure. You
can supply a maximum of thirty arguments.
Remarks
You can set a reference to the Microsoft Access type library from any other ActiveX component
and use the objects, methods, and properties defined in that library in your code. However,
you can't set a reference to an individual Microsoft Access database from any application
other than Microsoft Access. The Run method provides a way to call a procedure you have
defined in a Microsoft Access database from another application.
Example
Suppose you have defined a procedure named NewForm in a database with its ProjectName
property set to "WizCode." The NewForm procedure takes a string argument. You can call
NewForm in the following manner from Visual Basic:
Dim appAccess As New Access.Application
appAccess.OpenCurrentDatabase ("C:\My Documents\WizCode.mdb")
appAccess.Run "WizCode.NewForm", "Some String"
If another procedure with the same name may reside in a different database, qualify the
procedure argument, as shown in the preceding example, with the name of the database in
which the desired procedure resides.
You can also use the Run method to call a procedure in a referenced Microsoft Access
database from another database.
Microsoft Access ignores any value returned by a procedure called by the Run method.
Example
The following example runs a user-defined Sub procedure in a module in a Microsoft Access
database from another application that acts as an Active X component.
To try this example, create a new database called WizCode.mdb and set its ProjectName
property to WizCode. Open a new module in that database and enter the following code.
Save the module, and close the database.
Sub Greeting(strName As String)
MsgBox("Hello, " & strName)
End Sub
In Microsoft Excel or Visual Basic, add the reference:
Tools menu -> References -> References dialog -> Microsoft Access 8.0 Object Library.
then run the following code from the same..
' Include in Declarations section of module.
Dim appAccess As Access.Application
Sub RunAccessSub()
' Create instance of Access Application object.
Set appAccess = _
CreateObject("Access.Application.8")
' Open WizCode database in Microsoft Access window.
appAccess.OpenCurrentDatabase "C:\My Documents\WizCode.mdb", False
' Run Sub procedure.
appAccess.Run "Greeting", "Joe"
Set appAccess = Nothing
End Sub
METHOD - RunCommand
also see.. Constants - RunCommand
The RunCommand method runs a built-in menu or toolbar command.
Syntax
[object.]RunCommand command
The RunCommand method has the following arguments.
Argument Description
object Optional. The Application object or DoCmd object.
command An intrinsic constant that specifies which built-in menu or toolbar
command is to be run.
Remarks
Each menu and toolbar command in Microsoft Access has an associated constant that you can
use with the RunCommand method to run that command from Visual Basic.
For a list of possible constants for the command argument, see RunCommand Method Constants.
or view these constants in the Object Browser -> Project/Library box ->
Access -> Classes list -> AcCommand. The constants appear in the Members Of list.
You can't use the RunCommand method to run a command on a custom menu or toolbar. You can
only use it with built-in menus and toolbars.
The RunCommand method replaces the DoMenuItem method of the DoCmd object.
Example
The following example uses the RunCommand method to open the Options dialog box (available
by clicking Options on the Tools menu):
Function OpenOptionsDialog() As Boolean
On Error GoTo Error_OpenOptionsDialog
DoCmd.RunCommand acCmdOptions
OpenOptionsDialog = True
Exit_OpenOptionsDialog:
Exit Function
Error_OpenOptionsDialog:
MsgBox Err & ": " & Err.Description
OpenOptionsDialog = False
Resume Exit_OpenOptionsDialog
End Function
METHOD - RunSQL
The RunSQL method carries out the RunSQL action in Visual Basic. For more information on
how the action and its arguments work, see the action topic.
Syntax
DoCmd.RunSQL sqlstatement[, usetransaction]
The RunSQL method has the following arguments.
Argument Description
sqlstatement A string expression that's a valid SQL statement for an action
query or a data-definition query. It uses an INSERT INTO, DELETE,
SELECT...INTO, UPDATE, CREATE TABLE, ALTER TABLE, DROP TABLE, CREATE
INDEX, or DROP INDEX statement. Include an IN clause if you want to
access another database.
usetransaction Use True (–1) to include this query in a transaction. Use False (0)
if you don't want to use a transaction. If you leave this argument
blank, the default (True) is assumed.
Remarks
The maximum length of the sqlstatement argument is 32,768 characters (unlike the SQL
Statement action argument in the Macro window, whose maximum length is 256 characters).
If you leave the usetransaction argument blank, don't use a comma following the
sqlstatement argument.
Example
The following example updates the Employees table, changing each sales manager's title
to Regional Sales Manager:
DoCmd.RunSQL "UPDATE Employees " & _
"SET Employees.Title = 'Regional Sales Manager' " & _
"WHERE Employees.Title = 'Sales Manager';"
METHOD - SetFocus
The SetFocus method moves the focus to the specified form, the specified control on the
active form, or the specified field on the active datasheet.
Syntax
object.SetFocus
The SetFocus method has the following argument.
Argument Description
object A Form object that represents a form, or a Control object that represents a
control on the active form or datasheet.
Remarks
You can use the SetFocus method when you want a particular field or control to have the
focus so that all user input is directed to this object.
In order to read some of the properties of a control, you need to ensure that the control
has the focus. For example, a text box must have the focus before you can read its Text
property.
Other properties can be set only when a control doesn't have the focus. For example, you
can't set a control's Visible or Enabled properties to False (0) when that control has the
focus.
You can also use the SetFocus method to navigate in a form according to certain conditions.
For example, if the user selects Not applicable for the first of a set of questions on a
form that's a questionnaire, your Visual Basic code might then automatically skip the
questions in that set and move the focus to the first control in the next set of questions.
You can move the focus only to a visible control or form. A form and controls on a form
aren't visible until the form's Load event has finished. Therefore, if you use the SetFocus
method in a form's Load event to move the focus to that form, you must use the Repaint
method before the SetFocus method.
You can't move the focus to a control if its Enabled property is set to False. You must
set a control's Enabled property to True (–1) before you can move the focus to that
control. You can, however, move the focus to a control if its Locked property is set to True.
If a form contains controls for which the Enabled property is set to True, you can't move
the focus to the form itself. You can only move the focus to controls on the form. In
this case, if you try to use SetFocus to move the focus to a form, the focus is set to
the control on the form that last received the focus.
Tip
You can use the SetFocus method to move the focus to a subform, which is a type of
control. You can also move the focus to a control on a subform by using the SetFocus method
twice, moving the focus first to the subform and then to the control on the subform.
Example
This example uses the Set statement to assign object references to variables. YourObject
is assumed to be a valid object with a Text property.
Dim YourObject, MyObject, MyStr
Set MyObject = YourObject ' Assign object reference.
' MyObject and YourObject refer to the same object.
YourObject.Text = "Hello World" ' Initialize property.
MyStr = MyObject.Text ' Returns "Hello World".
' Discontinue association. MyObject no longer refers to YourObject.
Set MyObject = Nothing ' Release the object.
Null values in Calculated Fields, working with..
Examples
You enter the expression in the Field cell in the query design grid. The fields you
reference in the expression are from the tables or queries in the current query.
Expression
Description
CurrentCountry: IIf(IsNull([Country]), " ", [Country])
Uses the IIf and IsNull functions to display an empty string in the CurrentCountry field if
the Country field is Null; otherwise, it displays the contents of the Country field.
LeadTime: IIf(IsNull([RequiredDate] - [ShippedDate]),
"Check for a missing date", [RequiredDate] - [ShippedDate])
Uses the IIf and IsNull functions to display in the LeadTime field the message "Check for a
missing date" if the value of either the RequiredDate or ShippedDate fields is Null;
otherwise, it displays the difference.
SixMonthSales: Nz([Qtr1Sales]) + Nz([Qtr2Sales])
Displays in the SixMonthSales field the total of the values in the first- and second-quarter
sales fields combined, using the Nz function to convert the Null values to zero first.
IIf(IsNull([UnitPrice]),0,[UnitPrice])
Changes a Null value to a zero (0) in the UnitPrice field.
Note
When you use an arithmetic operator (+, -, *, /) in an expression and the value of one of
the fields in the expression is Null, the result of the entire expression will be Null.
If some records in one of the fields you used in the expression might have a Null value,
you can convert the Null value to zero by using the Nz function, as shown in the preceding
OBJECT - Application
The Application object refers to the active Microsoft Access application.
Object Model: [Objects and *(Objects and Collections)]
Application
|-*Forms
| |-*Controls
|-*Reports
| |-*Controls
|-*Modules
|-Screen
|-DoCmd
Methods Properties
AccessError Application (Access)
AddToFavorites CodeContextObject
BuildCriteria CommandBar
CloseCurrentDatabase CurrentObjectType
DefaultWorkspaceClone CurrentObjectName
Echo DBEngine
FollowHyperlink MenuBar
GetOption, SetOption Parent (Access)
NewCurrentDatabase ShortcutMenuBar
OpenCurrentDatabase UserControl
Quit Visible (Access)
RefreshDatabaseWindow
Run
RunCommand
Remarks
The Application object contains all Microsoft Access objects and collections, including
the Forms collection, the Reports collection, the Modules collection, the References
collection, the Screen object, and the DoCmd object.
You can use the Application object to apply methods or property settings to the entire
Microsoft Access application. For example, you can use the SetOption method of the
Application object to set database options from Visual Basic. The following example
shows how you can set the Status Bar check box under Show on the View tab of the Options
dialog box.
Application.SetOption "Show Status Bar", True
Microsoft Access is an ActiveX component that supports Automation, formerly called OLE
Automation. You can manipulate Microsoft Access objects from another application that
also supports Automation. To do this, you use the Application object.
For example, Microsoft Visual Basic is an ActiveX component. You can open a Microsoft
Access database from Visual Basic and work with its objects. From Visual Basic, first
create a reference to the Microsoft Access 8.0 object library. Then create a new instance
of the Application class and point an object variable to it, as in the following example:
Dim appAccess As New Access.Application
From applications that don't support the New keyword, you can create a new instance of
the Application class by using the CreateObject function:
Dim appAccess As Object
Set appAccess = CreateObject("Access.Application.8")
Once you've created a new instance of the Application class, you can open a database or
create a new database, by using either the OpenCurrentDatabase method or the
NewCurrentDatabase method. You can then set the properties of the Application object
and call its methods. When you return a reference to the DBEngine object by using the
DBEngine property of the Application object, you can access all DAO objects and collections
by using this reference.
You can also manipulate other Microsoft Access objects through the Application object.
For example, by using the OpenForm method of the Microsoft Access DoCmd object, you can
open a Microsoft Access form from Microsoft Excel:
appAccess.DoCmd.OpenForm "Orders"
For more information on creating a reference and controlling objects by using Automation,
see the documentation for the application that's acting as the ActiveX component.
Example
The following example prints some current property settings of the Application object,
sets an option, and then quits the application, saving all objects:
Sub ApplicationInformation()
' Print name and type of current object.
Debug.Print Application.CurrentObjectName
Debug.Print Application.CurrentObjectType
' Set Hidden Objects option under Show on View tab of Options dialog box.
Application.SetOption "Show Hidden Objects", True
' Quit Microsoft Access, saving all objects.
Application.Quit acSaveYes
End Sub
The next example shows how to use Microsoft Access as an ActiveX component. From Microsoft
Excel, Visual Basic, or another application that acts as an ActiveX component, create a
reference to Microsoft Access by clicking References on the Tools menu in the Module window.
Select the check box next to Microsoft Access 8.0 Object Library. Then enter the following
code in a Visual Basic module within that application and call the GetAccessData procedure.
The example passes a database name and report name to a procedure that creates a new
instance of the Application class, opens the database, and prints the specified report.
' Declare object variable in declarations section of a module
Dim appAccess As Access.Application
Sub GetAccessData()
Dim strDB As String
Dim strReportName As String
' Initialize string to database path.
strDB = "C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb"
' Initialize string to Report name.
strReportName = "Catalog"
PrintAccessReport strDB, strReportName
End Sub
Sub PrintAccessReport(strDB As String, strReportName As String)
' Return reference to Microsoft Access Application object.
Set appAccess = New Access.Application
' Open database in Microsoft Access.
appAccess.OpenCurrentDatabase strDB
' Print report.
appAccess.DoCmd.OpenReport strReportName
MsgBox "Click OK when " & strReportName & _
" is finished printing"
appAccess.CloseCurrentDatabase
Set appAccess = Nothing
End Sub
OBJECT - Collection
A Collection object is an ordered set of items that can be referred to as a unit.
Methods Properties
Add (VBA) Count (VBA)
Item
Remove (VBA)
Remarks
The Collection object provides a convenient way to refer to a related group of items as
a single object. The items, or members, in a collection need only be related by the fact
that they exist in the collection. Members of a collection don't have to share the same
data type.
A collection can be created the same way other objects are created. For example:
Dim X As New Collection
Once a collection is created, members can be added using the Add method and removed
using the Remove method. Specific members can be returned from the collection using
the Item method, while the entire collection can be iterated using the
For Each...Next statement.
Specifics
In Microsoft Access, a Collection object can consist of a set of objects of any type.
You can create a Collection object that consists of several objects of the same type
or objects of different types.
The collection defined by a Collection object can contain any combination of Microsoft
Access objects, data access objects, and objects from any other application that exposes
its objects to Microsoft Access. You can also add a Collection object to a collection
defined by a Collection object.
The collection can also contain user-defined objects that you create in Microsoft Access.
For example, you can create user-defined objects with custom methods and properties from
a form module or report module. Then you can add these objects to a collection defined by
a Collection object, and manipulate them as a set.
Example
This example creates a Collection object (MyClasses), and then creates a dialog box in
which users can add objects to the collection. To see how this works, choose the Class
Module command from the Insert menu and declare a public variable called InstanceName
at module level of Class1 (type Public InstanceName) to hold the names of each instance.
Leave the default name as Class1. Copy and paste the following code into the General
section of another module, and then start it with the statement ClassNamer in another
procedure. (This example only works with host applications that support classes.)
Sub ClassNamer()
Dim MyClasses As New Collection ' Create a Collection object.
Dim Num ' Counter for individualizing keys.
Dim Msg As String ' Variable to hold prompt string.
Dim TheName, MyObject, NameList ' Variants to hold information.
Do
Dim Inst As New Class1 ' Create a new instance of Class1.
Num = Num + 1 ' Increment Num, then get a name.
Msg = "Please enter a name for this object." & Chr(13) _
& "Press Cancel to see names in collection."
TheName = InputBox(Msg, "Name the Collection Items")
Inst.InstanceName = TheName ' Put name in object instance.
' If user entered name, add it to the collection.
If Inst.InstanceName <> "" Then
' Add the named object to the collection.
MyClasses.Add item := Inst, key := CStr(Num)
End If
' Clear the current reference in preparation for next one.
Set Inst = Nothing
Loop Until TheName = ""
' Create list of names.
For Each MyObject In MyClasses
NameList = NameList & MyObject.InstanceName & Chr(13)
Next MyObject
' Display the list of names in a message box.
MsgBox NameList, , "Instance Names In MyClasses Collection"
' Remove name from the collection. Since collections are reindexed
' automatically, remove the first member on each iteration.
For Num = 1 To MyClasses.Count
MyClasses.Remove 1
Next
End Sub
OBJECT - Data Access Objects & Collections Reference
DAO objects and collections provide a framework for using code to create and manipulate
components of your database system. Objects and collections have properties that describe
the characteristics of database components and methods that you use to manipulate them.
Together these objects and collections form a hierarchical model of your database structure,
which you can control programmatically.
Objects and collections provide different types of containment relations: Objects contain
zero or more collections, all of different types; and collections contain zero or more
objects, all of the same type. Although objects and collections are similar entities, the
distinction differentiates the two types of relations.
In the following table, the type of collection in the first column contains the type of
object in the second column. The third column describes what each type of object represents.
Collection Object Description
Connections Connection Information about a connection to an ODBC data source
(ODBCDirect workspaces only)
Containers Container Storage for information about a predefined object type
(Microsoft Jet workspaces only)
Databases Database An open database
None DBEngine The Microsoft Jet database engine
Documents Document Information about a saved, predefined object (Microsoft
Jet workspaces only)
Errors Error Information about any errors associated with this object
Fields Field A column that is part of a table, query, index, relation,
or recordset
Groups Group A group of user accounts (Microsoft Jet workspaces only)
Indexes Index Predefined ordering and uniqueness of values in a table
(Microsoft Jet workspaces only)
Parameters Parameter A parameter for a parameter query
Properties Property A built-in or user-defined property
QueryDefs QueryDef A saved query definition
Recordsets Recordset The records in a base table or query
Relations Relation A relationship between fields in tables and queries
(Microsoft Jet workspaces only)
TableDefs TableDef A saved table definition (Microsoft Jet workspaces only)
Users User A user account (Microsoft Jet workspaces only)
Workspaces Workspace A session of the Microsoft Jet database engine
OBJECT - DoCmd
(1 of 2; see..2)
You can use the methods of the DoCmd object to run Microsoft Access actions from Visual
Basic. An action performs tasks such as closing windows, opening forms, and setting the
value of controls. For example, you can use the OpenForm method of the DoCmd object to
open a form, or use the Hourglass method to change the mouse pointer to an hourglass icon.
Note
The DoCmd object replaces the DoCmd statement from versions 1.x and 2.0 of Microsoft
Access. The actions that were used as arguments for the DoCmd statement are now methods of
the DoCmd object. For example, in Microsoft Access 2.0, you could have used the code DoCmd
OpenForm "Orders" to open a form from Access Basic. In Microsoft Access 97, you would use
the following syntax:
DoCmd.OpenForm "Orders"
Syntax
[application.]DoCmd.method [arg1, arg2, ...]
The DoCmd object has the following arguments.
Argument Description
application Optional. The Application object.
method One of the methods supported by this object.
arg1, arg2, ... The arguments for the selected method. These arguments are the same as
the action arguments for the corresponding action.
Remarks
Most of the methods of the DoCmd object have arguments; some are required, while others
are optional. If you omit optional arguments, the arguments assume the default values for
the particular method. For example, the OpenForm method uses seven arguments, but only
the first argument, formname, is required. The following example shows how you can open
the Employees form in the current database. Only employees with the title Sales
Representative are included.
DoCmd.OpenForm "Employees", , ,"[Title] = 'Sales Representative'"
The DoCmd object doesn't support methods corresponding to the following actions:
· AddMenu.
· MsgBox. Use the MsgBox function.
· RunApp. Use the Shell function to run another application.
· RunCode. Run the function directly in Visual Basic.
· SendKeys. Use the SendKeys statement.
· SetValue. Set the value directly in Visual Basic.
· StopAllMacros.
· StopMacro.
Example
The following example opens a form in Form view and moves to a new record.
Sub ShowNewRecord()
DoCmd.OpenForm "Employees", acNormal
DoCmd.GoToRecord , , acNewRec
End Sub
For more information on the Microsoft Access action corresponding to a DoCmd method,
search the Help index for the name of the action
OBJECT - DoCmd
(2 of 2; see..1)
Object Model:
Application
|-DoCmd
You can use the methods of the DoCmd object to run Microsoft Access actions from Visual
Basic. An action performs tasks such as closing windows, opening forms, and setting the
value of controls. For example, you can use the OpenForm method of the DoCmd object to
open a form, or use the Hourglass method to change the mouse pointer to an hourglass icon.
Syntax
[application.]DoCmd.method [arg1, arg2, ...]
Argument Description
application Optional. The Application object.
method One of the methods supported by this object.
arg1, arg2, ... The arguments for the selected method. These arguments are the
same as the action arguments for the corresponding action.
For example:
DoCmd.OpenForm "Orders"
Methods
ApplyFilter
Beep
CancelEvent
Close
CopyObject
DeleteObject
DoMenuItem
Echo
FindNext
FindRecord
GoToControl
GoToPage
GoToRecord
Hourglass
Maximize
Minimize
MoveSize
OpenForm
OpenModule
OpenQuery
OpenReport
OpenTable
OutputTo
PrintOut
Quit
Rename
RepaintObject
Requery
Restore
RunCommand
RunMacro
RunSQL
Save
SelectObject
SendObject
SetMenuItem
SetWarnings
ShowAllRecords
ShowToolbar
TransferDatabase
TransferSpreadsheet
TransferText
Remarks
Most of the methods of the DoCmd object have arguments ľ some are required, while others
are optional. If you omit optional arguments, the arguments assume the default values for
the particular method. For example, the OpenForm method uses seven arguments, but only the
first argument, formname, is required. The following example shows how you can open the
Employees form in the current database. Only employees with the title Sales Representative
are included.
DoCmd.OpenForm "Employees", , ,"[Title] = 'Sales Representative'"
The DoCmd object doesn't support methods corresponding to the following actions:
· AddMenu.
· MsgBox. Use the MsgBox function.
· RunApp. Use the Shell function to run another application.
· RunCode. Run the function directly in Visual Basic.
· SendKeys. Use the SendKeys statement.
· SetValue. Set the value directly in Visual Basic.
· StopAllMacros.
· StopMacro.
For more information on the Microsoft Access action corresponding to a DoCmd method,
search the Help index for the name of the action.
Example
.. open a form in Form view and move to a new record.
Sub ShowNewRecord()
DoCmd.OpenForm "Employees", acNormal
DoCmd.GoToRecord , , acNewRec
End Sub
OBJECT - Parameter (DAO)
A Parameter object represents a value supplied to a query. The parameter is associated
with a QueryDef object created from a parameter query.
Object Model:
QueryDef
|-Parameters
|-Parameter
Remarks
Parameter objects allow you to change the arguments in a frequently run QueryDef object
without having to recompile the query.
Using the properties of a Parameter object, you can set a query parameter that can be
changed before the query is run. You can:
· Use the Name property to return the name of a parameter.
· Use the Value property to set or return the parameter values to be used in the query.
· Use the Type property to return the data type of the Parameter object.
· Use the Direction property to set or return whether the parameter is an input parameter,
an output parameter, or both.
In an ODBCDirect workspace, you can also:
· Change the setting of the Type property. Doing so will also clear the Value property.
· Use the Direction property to set or return whether the parameter is an input parameter,
an output parameter, or both.
Example (DAO)
This example demonstrates Parameter objects and the Parameters collection by creating a
temporary QueryDef and retrieving data based on changes made to the QueryDef object's
Parameters. The ParametersChange procedure is required for this procedure to run.
Sub ParameterX()
Dim dbsNorthwind As Database
Dim qdfReport As QueryDef
Dim prmBegin As Parameter
Dim prmEnd As Parameter
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
' Create temporary QueryDef object with two parameters.
Set qdfReport = dbsNorthwind.CreateQueryDef("", _
"PARAMETERS dteBegin DateTime, dteEnd DateTime; " & _
"SELECT EmployeeID, COUNT(OrderID) AS NumOrders " & _
"FROM Orders WHERE ShippedDate BETWEEN " & _
"[dteBegin] AND [dteEnd] GROUP BY EmployeeID " & _
"ORDER BY EmployeeID")
Set prmBegin = qdfReport.Parameters!dteBegin
Set prmEnd = qdfReport.Parameters!dteEnd
' Print report using specified parameter values.
ParametersChange qdfReport, prmBegin, #1/1/95#, _
prmEnd, #6/30/95#
ParametersChange qdfReport, prmBegin, #7/1/95#, _
prmEnd, #12/31/95#
dbsNorthwind.Close
End Sub
Sub ParametersChange(qdfTemp As QueryDef, _
prmFirst As Parameter, dteFirst As Date, _
prmLast As Parameter, dteLast As Date)
' Report function for ParameterX.
Dim rstTemp As Recordset
Dim fldLoop As Field
' Set parameter values and open recordset from temporary QueryDef object.
prmFirst = dteFirst
prmLast = dteLast
Set rstTemp = _
qdfTemp.OpenRecordset(dbOpenForwardOnly)
Debug.Print "Period " & dteFirst & " to " & dteLast
' Enumerate recordset.
Do While Not rstTemp.EOF
' Enumerate Fields collection of recordset.
For Each fldLoop In rstTemp.Fields
Debug.Print " - " & fldLoop.Name & " = " & fldLoop;
Next fldLoop
Debug.Print
rstTemp.MoveNext
Loop
rstTemp.Close
End Sub
Example (Access)
The following example creates a new parameter query and supplies values for the parameters:
Sub NewParameterQuery()
Dim dbs As Database, qdf As QueryDef, rst As Recordset
Dim prm As Parameter, strSQL As String
' Return reference to current database.
Set dbs = CurrentDb
' Construct SQL string.
strSQL = "PARAMETERS [Beginning OrderDate] DateTime, " _
& "[Ending OrderDate] DateTime; SELECT * FROM Orders " & _
"WHERE (OrderDate Between[Beginning OrderDate] " _
& "And [Ending OrderDate]);"
' Create new QueryDef object.
Set qdf = dbs.CreateQueryDef("ParameterQuery", strSQL)
' Supply values for parameters.
qdf.Parameters![Beginning OrderDate] = #4/1/95#
qdf.Parameters![Ending OrderDate] = #4/30/95#
' Open recordset on QueryDef object.
Set rst = qdf.OpenRecordset
rst.MoveLast
MsgBox "Query returned " & rst.RecordCount & " records."
rst.Close
Set dbs = Nothing
End Sub
OBJECT - QueryDef
A QueryDef object is a stored definition of a query in a Microsoft Jet database, or a
temporary definition of a query in an ODBCDirect workspace.
Connection
|----Database
|-------|----QueryDefs
|---QueryDef
|----Paramters
|----Fields
Remarks
You can use the QueryDef object to define a query. For example, you can:
· Use the SQL property to set or return the query definition.
· Use the QueryDef object's Parameters collection to set or return query parameters.
· Use the Type property to return a value indicating whether the query selects records
from an existing table, makes a new table, inserts records from one table into another
table, deletes records, or updates records.
· Use the MaxRecords property to limit the number of records returned from a query.
· Use the ODBCTimeout property to indicate how long to wait before the query returns
records. The ODBCTimeout property applies to any query that accesses ODBC data.
In a Microsoft Jet workspace, you can also:
· Use the ReturnsRecords property to indicate that the query returns records. The
ReturnsRecords property is only valid on SQL pass-through queries.
· Use the Connect property to make an SQL pass-through query to an ODC database.
In an ODBCDirect workspace, you can also:
· Use the Prepare property to determine whether to invoke the ODBC SQLPrepare API when the
query is executed.
· Use the CacheSize property to cache records returned from a query.
You can also create temporary QueryDef objects. Unlike permanent QueryDef objects,
temporary QueryDef objects are not saved to disk or appended to the QueryDefs collection.
Temporary QueryDef objects are useful for queries that you must run repeatedly during
run time but do not not need to save to disk, particularly if you create their SQL
statements during run time.
You can think of a permanent QueryDef object in a Microsoft Jet workspaces as a compiled
SQL statement. If you execute a query from a permanent QueryDef object, the query will run
faster than if you run the equivalent SQL statement from the OpenRecordset method. This is
because the Microsoft Jet database engine doesn't need to compile the query before executing
it.
The preferred way to use the native SQL dialect of an external database engine accessed
through the Microsoft Jet database engine is through QueryDef objects. For example, you can
create a Microsoft SQL Server query and store it in a QueryDef object. When you need to use
a non-Microsoft Jet database engine SQL query, you must provide a Connect property string
that points to the external data source. Queries with valid Connect properties bypass the
Microsoft Jet database engine and pass the query directly to the external database server for
processing.
To create a new QueryDef object, use the CreateQueryDef method. In a Microsoft Jet workspace,
if you supply a string for the name argument or if you explicitly set the Name property of
the new QueryDef object to a non–zero-length string, you will create a permanent QueryDef that
will automatically be appended to the QueryDefs collection and saved to disk. Supplying a
zero-length string as the name argument or explicitly setting the Name property to a zero-length
string will result in a temporary QueryDef object.
In an ODBCDirect workspace, a QueryDef is always temporary. The QueryDefs collection contains
all open QueryDef objects. When a QueryDef is closed, it is automatically removed from the
QueryDefs collection.
To refer to a QueryDef object in a collection by its ordinal number or by its Name property
setting, use any of the following syntax forms:
QueryDefs(0)
QueryDefs("name")
QueryDefs![name]
You can refer to temporary QueryDef objects only by the object variables that you have
assigned to them.
Example (DAO)
This example uses the CreateQueryDef method to create and execute both a temporary and
a permanent QueryDef. The GetrstTemp function is required for this procedure to run.
Sub CreateQueryDefX()
Dim dbsNorthwind As Database
Dim qdfTemp As QueryDef
Dim qdfNew As QueryDef
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
With dbsNorthwind
' Create temporary QueryDef.
Set qdfTemp = .CreateQueryDef("", _
"SELECT * FROM Employees")
' Open Recordset and print report.
GetrstTemp qdfTemp
' Create permanent QueryDef.
Set qdfNew = .CreateQueryDef("NewQueryDef", _
"SELECT * FROM Categories")
' Open Recordset and print report.
GetrstTemp qdfNew
' Delete new QueryDef because this is a demonstration.
.QueryDefs.Delete qdfNew.Name
.Close
End With
End Sub
Function GetrstTemp(qdfTemp As QueryDef)
Dim rstTemp As Recordset
With qdfTemp
Debug.Print .Name
Debug.Print " " & .SQL
' Open Recordset from QueryDef.
Set rstTemp = .OpenRecordset(dbOpenSnapshot)
With rstTemp
' Populate Recordset and print number of records.
.MoveLast
Debug.Print " Number of records = " & _
.RecordCount
Debug.Print
.Close
End With
End With
End Function
Example (DAO with collections)
This example creates a new QueryDef object and appends it to the QueryDefs collection of
the Northwind Database object. It then enumerates the QueryDefs collection and the Properties
collection of the new QueryDef.
Sub QueryDefX()
Dim dbsNorthwind As Database
Dim qdfNew As QueryDef
Dim qdfLoop As QueryDef
Dim prpLoop As Property
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
' Create new QueryDef object. Because it has a
' name, it is automatically appended to the
' QueryDefs collection.
Set qdfNew = dbsNorthwind.CreateQueryDef("NewQueryDef", _
"SELECT * FROM Categories")
With dbsNorthwind
Debug.Print .QueryDefs.Count & _
" QueryDefs in " & .Name
' Enumerate QueryDefs collection.
For Each qdfLoop In .QueryDefs
Debug.Print " " & qdfLoop.Name
Next qdfLoop
With qdfNew
Debug.Print "Properties of " & .Name
' Enumerate Properties collection of new
' QueryDef object.
For Each prpLoop In .Properties
On Error Resume Next
Debug.Print " " & prpLoop.Name & " - " & _
IIf(prpLoop = "", "[empty]", prpLoop)
On Error Goto 0
Next prpLoop
End With
' Delete new QueryDef because this is a
' demonstration.
.QueryDefs.Delete qdfNew.Name
.Close
End With
End Sub
Example (Access with collections)
The following example checks to see if there is a query called RecentHires in the current
database, and deletes it from the QueryDefs collection if it exists. Then the procedure
creates a new QueryDef object and opens it in Datasheet view.
Sub NewQuery()
Dim dbs As Database, qdf As QueryDef
Dim strSQL As String
' Return reference to current database.
Set dbs = CurrentDb
' Refresh QueryDefs collection.
dbs.QueryDefs.Refresh
' If RecentHires query exists, delete it.
For Each qdf in dbs.QueryDefs
If qdf.Name = "RecentHires" Then
dbs.QueryDefs.Delete qdf.Name
End If
Next qdf
' Create SQL string to select employees hired on or after 1-1-94.
strSQL = "SELECT * FROM Employees WHERE HireDate >= #1-1-94#;"
' Create new QueryDef object.
Set qdf = dbs.CreateQueryDef("RecentHires", strSQL)
' Open query in Datasheet view.
DoCmd.OpenQuery qdf.Name
Set dbs = Nothing
End Sub
OBJECT - Reference object
The Reference object refers to a reference set to another application's or project's
type library.
Remarks
When you create a Reference object, you set a reference dynamically from Visual Basic.
The Reference object is a member of the References collection. To refer to a particular
Reference object in the References collection, use any of the following syntax forms.
Syntax Description
References!referencename The referencename argument is the name of the Reference
object.
References("referencename") The referencename argument is the name of the Reference
object.
References(index) The index argument is the object's numerical position
within the collection.
The following example refers to the Reference object that represents the reference to the
Microsoft Access type library:
Dim ref As Reference
Set ref = References!Access
Example
The following example creates a reference to a specified type library:
Function ReferenceFromFile(strFileName As String) As Boolean
Dim ref As Reference
On Error GoTo Error_ReferenceFromFile
Set ref = References.AddFromFile(strFileName)
ReferenceFromFile = True
Exit_ReferenceFromFile:
Exit Function
Error_ReferenceFromFile:
MsgBox Err & ": " & Err.Description
ReferenceFromFile = False
Resume Exit_ReferenceFromFile
End Function
You could call this function by using a procedure such as the following, which creates a
reference to the calendar control:
Sub CreateCalendarReference()
If ReferenceFromFile("C:\Windows\System\Mscal.ocx") = True Then
MsgBox "Reference set successfully."
Else
MsgBox "Reference not set successfully."
End If
End Sub
OBJECT - Workspace
Methods Properties
BeginTrans, CommitTrans, Rollback DefaultCursorDriver (DAO)
Close IsolateODBCTrans
CreateDatabase LoginTimeout
CreateGroup Name
CreateUser Type
OpenConnection UserName
OpenDatabase
A Workspace object defines a named session for a user. It contains open databases and
provides mechanisms for simultaneous transactions and, in Microsoft Jet workspaces,
secure workgroup support. It also controls whether you are going through the Microsoft
Jet database engine or ODBCDirect to access external data.
DBEngine
|-Workspaces
|-Workspace
|-Connections
|-Databases
|-Groups
|-Users
Remarks
A Workspace is a non-persistent object that defines how your application interacts with
data — either by using the Microsoft Jet database engine, or ODBCDirect. Use the Workspace
object to manage the current session or to start an additional session. In a session,
you can open multiple databases or connections, and manage transactions. For example,
you can:
· Use the Name, UserName, and Type properties to establish a named session. The session
creates a scope in which you can open multiple databases and conduct one instance of
nested transactions.
· Use the Close method to terminate a session.
· Use the OpenDatabase method to open one or more existing databases on a Workspace.
· Use the BeginTrans, CommitTrans, and Rollback methods to manage nested transaction
processing within a Workspace and use several Workspace objects to conduct multiple,
simultaneous, and overlapping transactions.
Further, using a Microsoft Jet database, you can establish security based on user names
and passwords:
· Use the Groups and Users collections to establish group and user access permissions to
objects in the Workspace.
· Use the IsolateODBCTrans property to isolate multiple transactions that involve the same
Microsoft Jet-connected ODBC database.
Note
For a complete list of all methods, properties, and collections available on a Workspace
object in either a Microsoft Jet database or an ODBCDirect database, see the Summary topic.
When you first refer to or use a Workspace object, you automatically create the default
workspace, DBEngine.Workspaces(0). The settings of the Name and UserName properties of
the default workspace are "#Default Workspace#" and "Admin," respectively. If security
is enabled, the UserName property setting is the name of the user who logged on.
To establish an ODBCDirect Workspace object, and thereby avoid loading the Microsoft Jet
database engine into memory, set the DBEngine object's DefaultType property to dbUseODBC,
or set the type argument of the CreateWorkspace method to dbUseODBC.
When you use transactions, all databases in the specified Workspace are affected — even
if multiple Database objects are opened in the Workspace. For example, you use a BeginTrans
method, update several records in a database, and then delete records in another database.
If you then use the Rollback method, both the update and delete operations are canceled and
rolled back. You can create additional Workspace objects to manage transactions independently
across Database objects.
You can create Workspace objects with the CreateWorkspace method. After you create a new
Workspace object, you must append it to the Workspaces collection if you need to refer to
it from the Workspaces collection.
You can use a newly created Workspace object without appending it to the Workspaces
collection. However, you must refer to it by the object variable to which you have
assigned it.
To refer to a Workspace object in a collection by its ordinal number or by its Name
property setting, use any of the following syntax forms:
DBEngine.Workspaces(0)
DBEngine.Workspaces("name")
DBEngine.Workspaces![name]
Example
This example creates a new Microsoft Jet Workspace object and a new ODBCDirect Workspace
object and appends them to the Workspaces collection. It then enumerates the Workspaces
collections and the Properties collection of each Workspace object. See the methods and
properties of the Workspace object or Workspaces collection for additional examples.
Sub WorkspaceX()
Dim wrkNewJet As Workspace
Dim wrkNewODBC As Workspace
Dim wrkLoop As Workspace
Dim prpLoop As Property
' Create a new Microsoft Jet workspace.
Set wrkNewJet = CreateWorkspace("NewJetWorkspace", _
"admin", "", dbUseJet)
Workspaces.Append wrkNewJet
' Create a new ODBCDirect workspace.
Set wrkNewODBC = CreateWorkspace("NewODBCWorkspace", _
"admin", "", dbUseODBC)
Workspaces.Append wrkNewODBC
' Enumerate the Workspaces collection.
For Each wrkLoop In Workspaces
With wrkLoop
Debug.Print "Properties of " & .Name
' Enumerate the Properties collection of the new Workspace object.
For Each prpLoop In .Properties
On Error Resume Next
If prpLoop <> "" Then Debug.Print " " & _
prpLoop.Name & " = " & prpLoop
On Error GoTo 0
Next prpLoop
End With
Next wrkLoop
wrkNewJet.Close
wrkNewODBC.Close
End Sub
OLE - Action PROPERTY
You can use the Action property in Visual Basic to specify the operation to perform on an
OLE object.
Setting
The Action property uses the following settings.
Constant Description
acOLECreateEmbed Creates an embedded object. To use this setting, you must first
set the control's OLETypeAllowed property to acOLEEmbedded or
acOLEEither. Set the Class property to the type of OLE object you
want to create. You can use the SourceDoc property to use an
existing file as a template.
acOLECreateLink Creates a linked OLE object from the contents of a file. To use
this setting, you must first set the control's OLETypeAllowed and
SourceDoc properties. Set the OLETypeAllowed property to acOLELinked
or acOLEEither. The SourceDoc property specifies the file used to
create the OLE object. You can also set the control's SourceItem
property (for example, to specify a row-and-column range if the
object you're creating is a Microsoft Excel worksheet). When you
create an OLE object by using this setting, the control displays
a metafile graphic image of the file specified by the control's
SourceDoc property. If you save the OLE object, only the link
information, such as the name of the application that supplied the
object and the name of the linked file, is saved because the control
contains an image of the data but no source data.
acOLECopy Copies the object to the Clipboard. When you copy an OLE object to
the Clipboard, all the data and link information associated with the
object is placed on the Clipboard as well. You can copy both linked
and embedded objects onto the Clipboard. Using this setting is
equivalent to clicking Copy on the Edit menu.
acOLEPaste Pastes data from the Clipboard to the control. If the paste
operation is successful, the control's OLEType property is set to
acOLELinked or acOLEEmbedded. If the paste operation isn't successful,
the OLEType property is set to acOLENone. Using the acOLEPaste
setting is equivalent to clicking Paste on the Edit menu.
acOLEUpdate Retrieves the current data from the application that supplied the
object and displays that data as a metafile graphic in the control.
acOLEActivate Opens an OLE object for an operation, such as editing. To use this
setting, you must first set the control's Verb property. The Verb
property specifies the operation to perform when the OLE object is
activated.
acOLEClose Closes an OLE object and ends the connection with the application
that supplied the object. This setting applies to embedded objects
only. Using this setting is equivalent to clicking Close on the
object's Control menu.
acOLEDelete Deletes the specified OLE object and frees the associated memory.
This setting enables you to explicitly delete an OLE object. Objects
are automatically deleted when a form is closed or when the object
is updated to a new object. You can't use the Action property to
delete a bound OLE object from its underlying table or query.
acOLEInsertObjDlg Displays the Insert Object dialog box. In Form view or Datasheet
view, you display this dialog box to enable the user to create a new
object or to link or embed an existing object. You can use the
control's OLETypeAllowed property to determine the type of object
the user can create (with the constant acOLELinked, acOLEEmbedded,
or acOLEEither) by using this dialog box.
acOLEPasteSpecialDlg Displays the Paste Special dialog box. In Form view or Datasheet
view, you display this dialog box to enable the user to paste an
object from the Clipboard. The dialog box provides several options,
including pasting either a linked or embedded object. You can use
the control's OLETypeAllowed property to determine the type of object
that can be pasted (with the constant acOLELinked, acOLEEmbedded,
or acOLEEither) by using this dialog box.
acOLEFetchVerbs Updates the list of verbs an OLE object supports. To display the
list of verbs, use the ObjectVerbs and ObjectVerbsCount properties.
You can set the Action property only by using Visual Basic. The Action property setting
is an Integer data type value.
The Action property isn't available in Design view but can be read or set in other views.
Remarks
When a control's Enabled property is set to No or its Locked property is set to Yes, you
can't use some Action property settings. The following table indicates which settings are
allowed or not allowed under these conditions.
Setting Enabled = No Locked = Yes
acOLECreateEmbed Not allowed Not allowed
acOLECreateLink Not allowed Not allowed
acOLECopy Allowed Allowed
acOLEPaste Not allowed Not allowed
acOLEUpdate Not allowed Not allowed
acOLEActivate Allowed Allowed
acOLEClose Not allowed Allowed
acOLEDelete Not allowed Not allowed
acOLEInsertObjDlg Not allowed Not allowed
acOLEPasteSpecialDlg Not allowed Not allowed
acOLEFetchVerbs Not allowed Allowed
PROCEDURES - Arguments, Understanding Named and Optional
When you call a Sub or Function procedure, you can supply arguments positionally, in the
order they appear in the procedure's definition, or you can supply the arguments by name
without regard to position.
For example, the following Sub procedure takes three arguments:
Sub PassArgs(strName As String, intAge As Integer, dteBirth As Date)
Debug.Print strName, intAge, dteBirth
End Sub
You can call this procedure by supplying its arguments in the correct position, each
delimited by a comma, as shown in the following example:
PassArgs "Mary", 26, #2-21-69#
You can also call this procedure by supplying named arguments, delimiting each with a comma.
PassArgs intAge:=26, dteBirth:=#2/21/69#, strName:="Mary"
A named argument consists of an argument name followed by a colon and an equal sign (:=),
followed by the argument value.
Named arguments are especially useful when you are calling a procedure that has optional
arguments. If you use named arguments, you don't have to include commas to denote missing
positional arguments. Using named arguments makes it easier to keep track of which
arguments you passed and which you omitted.
Optional arguments are preceded by the Optional keyword in the procedure definition. You
can also specify a default value for the optional argument in the procedure definition.
For example:
Sub OptionalArgs(strState As String, Optional strCountry As String = "USA")
. . .
End Sub
When you call a procedure with an optional argument, you can choose whether or not to
specify the optional argument. If you don't specify the optional argument, the default
value, if any, is used. If no default value is specified, the argument is it would be
for any variable of the specified type.
The following procedure includes an optional argument, the varCountry variable. The
IsMissing function determines whether an optional argument has been passed to the
procedure.
Sub OptionalArgs(strState As String, Optional intRegion As Integer, _
Optional strCountry As String = "USA")
If IsMissing(intRegion) And IsMissing(strCountry) Then
Debug.Print strState
ElseIf IsMissing(strCountry) Then
Debug.Print strState, intRegion
ElseIf IsMissing(intRegion) Then
Debug.Print strState, strCountry
Else
Debug.Print strState, intRegion, strCountry
End If
End Sub
You can call this procedure using named arguments as shown in the following examples.
OptionalArgs strCountry:="USA", strState:="MD"
OptionalArgs strState:= "MD", intRegion:=5
PROPERTIES - Combo Box
The following list identifies the properties you can set for a combo box control. Those properties that apply only when the control is on a form are followed by (forms) for "Forms Only."
Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it in the property sheet, in a macro, or by using Visual Basic.
A–M
AddColon Enabled (forms)
AfterUpdate (forms) FontItalic
AllowAutoCorrect FontName
AutoExpand FontSize
AutoLabel FontUnderline
BackColor FontWeight
BackStyle ForeColor
BeforeUpdate (forms) Format
BorderColor Height
BorderStyle HelpContextID (forms)
BorderWidth InputMask
BoundColumn InSelection (forms)
Column ItemData
ColumnCount LabelAlign
ColumnHeads LabelX
ColumnWidths LabelY
ControlSource Left
ControlTipText (forms) LimitToList
ControlType ListRows
DecimalPlaces ListWidth
DefaultValue (forms) Locked (forms)
DisplayWhen (forms)
N–Z
Name RowSource
OnChange (forms) RowSourceType
OnClick (forms) ShortcutMenuBar
OnDblClick (forms) SpecialEffect
OnEnter (forms) StatusBarText (forms)
OnExit (forms) TabIndex (forms)
OnGotFocus (forms) TabStop (forms)
OnKeyDown (forms) Tag
OnKeyPress (forms) TextAlign
OnKeyUp (forms) Top
OnLostFocus (forms) ValidationRule (forms)
OnMouseDown (forms) ValidationText (forms)
OnMouseMove (forms) Visible
OnMouseUp (forms) Width
OnNotInList (forms)
PROPERTY - Filter
You can use the Filter property to specify a subset of records to be displayed when a filter
is applied to a form, query, or table.
Setting
The Filter property is a string expression consisting of a WHERE clause without the WHERE
keyword. For example, the following Visual Basic code defines and applies a filter to show
only customers from the USA:
Me.Filter = "Country = 'USA'"
Me.FilterOn = True
You can set this property by using a table's or form's property sheet, a macro, or Visual
Basic.
You can also set this property in Form view or Datasheet view by pointing to
Records menu -> Filter and clicking one of the submenu commands.
Note
Setting the Filter property has no effect on the DAO Filter property.
Remarks
You can use the Filter property to save a filter and apply it later. Filters are
saved with the objects in which they are created. They are automatically loaded when the
object is opened, but they aren't automatically applied.
When a new object is created, it inherits the RecordSource, Filter, OrderBy, and OrderByOn
properties of the table or query it was created from.
To apply a saved filter to a form, query, or table, you can toolbar -> Apply Filter,
Records menu -> Apply Filter/Sort, or use a macro or Visual Basic to set the
FilterOn property to True (–1). For reports, you can apply a filter by setting
the FilterOn property to Yes in the report's property sheet.
The Apply Filter button indicates the state of the Filter and FilterOn properties. The button
remains disabled until there is a filter to apply. If an existing filter is currently applied,
the Apply Filter button appears pressed in.
To apply a filter automatically when a form is opened, specify in the OnOpen event property
setting of the form either a macro that uses the ApplyFilter action or an event procedure
that uses the DoCmd.ApplyFilter.
You can remove a filter by clicking the pressed-in Apply Filter button,
Records menu -> Remove Filter/Sort, or using Visual Basic to set the
FilterOn property to False (0).
Note
You can save a filter as a query while in the Filter By Form window or the
Advanced Filter/Sort window through File menu -> Save As Query.
When the Filter property is set in form Design view, Microsoft Access does not attempt to
validate the SQL expression. If the SQL expression is invalid, an error occurs when the
filter is applied.
PROPERTY - Format
You can use the Format property to customize the way numbers, dates, times, and text
are displayed and printed. For example, if you've created a Price text box, you can
set its Format property to Currency and its DecimalPlaces property to 2 or Auto. If
you enter 4321.678 in the control, the number would be displayed as $4,321.68.
You can use one of the predefined formats or you can create a custom format by using
formatting symbols.
Setting
The Format property uses different settings for different data types. For information
about settings for a specific data type, see one of the following topics:
· Date/Time Data Type
· Number and Currency Data Types
· Text and Memo Data Types
· Yes/No Data Type
For a control, you can set this property in the control's property sheet. For a field,
you can set this property in table Design view (in the Field Properties section) or in
Design view of the Query window (in the Field Properties property sheet). You can also
use a macro or Visual Basic.
Note
In Visual Basic, enter a string expression that corresponds to one of the
predefined formats or enter a custom format.
Remarks
The Format property affects only how data is displayed. It doesn't affect how data is
stored.
Microsoft Access provides predefined formats for Date/Time, Number and Currency, Text
and Memo, and Yes/No data types. The predefined formats depend on the country specified
by double-clicking Regional Settings in Windows Control Panel. Microsoft Access displays
formats appropriate for the country selected. For example, with English (United States)
selected on the Regional Settings tab, 1234.56 in the Currency format appears as $1,234.56,
but when English (British) is selected on the Regional Settings tab, the number appears
as Ł1,234.56.
If you set a field's Format property in table Design view, Microsoft Access uses that
format to display data in datasheets. It also applies the field's Format property to new
controls on forms and reports.
You can use the following symbols in custom formats for any data type.
Symbol Meaning
(space) Display spaces as literal characters.
"ABC" Display anything inside quotation marks as literal characters.
! Force left alignment instead of right alignment.
* Fill available space with the next character.
\ Display the next character as a literal character. You can also display
literal characters by placing quotation marks around them.
[color] Display the formatted data in the color specified between the brackets.
Available colors: Black, Blue, Green, Cyan, Red, Magenta, Yellow, White.
You can't mix custom formatting symbols for the Number and Currency data types with
Date/Time, Yes/No, or Text and Memo formatting symbols.
When you have defined an input mask and set the Format property for the same data, the
Format property takes precedence when the data is displayed and the input mask is ignored.
For example, if you create a Password input mask in table Design view and also set the
Format property for the same field, either in the table or in a control on a form, the
Password input mask is ignored and the data is displayed according to the Format property.
Examples
The following three examples set the Format property by using a predefined format:
Me!Date.Format = "Medium Date"
Me!Time.Format = "Long Time"
Me!Registered.Format = "Yes/No"
The next example sets the Format property by using a custom format. This format
displays a date as: Jan 1995.
Forms!Employees!HireDate.Format = "mmm yyyy"
The following example demonstrates a Visual Basic function that formats numeric data
by using the Currency format and formats text data entirely in capital letters. The
function is called from the OnLostFocus event of an unbound control named TaxRefund.
Function FormatValue() As Integer
Dim varEnteredValue As Variant
varEnteredValue = Forms!Survey!TaxRefund.Value
If IsNumeric(varEnteredValue) = True Then
Forms!Survey!TaxRefund.Format = "Currency"
Else
Forms!Survey!TaxRefund.Format = ">"
End If
End Function
PROPERTIES - List Box Control
The following list identifies the properties you can set for a list box control.
Those properties that apply only when the control is on a form are followed by
(forms) for "Forms Only."
Click any name below to display additional information about that property, such as
other restrictions concerning when the property is available, and whether you can set
it in the property sheet, in a macro, or by using Visual Basic.
A-M
AddColon Enabled (forms)
AfterUpdate (forms) FontItalic
AutoLabel FontName
BackColor FontSize
BeforeUpdate (forms) FontUnderline
BorderColor FontWeight
BorderStyle ForeColor
BorderWidth Height
BoundColumn HelpContextID (forms)
Column (forms) control.Column(column, row) InSelection (forms)
ColumnCount ItemData
ColumnHeads LabelAlign
ColumnWidths LabelX
ControlSource LabelY
ControlTipText (forms) Left
ControlType Locked (forms)
DefaultValue (forms) MultiSelect
DisplayWhen (forms)
N-Z
Name RowSource
OnClick (forms) RowSourceType
OnDblClick (forms) ShortcutMenuBar
OnEnter (forms) SpecialEffect
OnExit (forms) StatusBarText (forms)
OnGotFocus (forms) TabIndex (forms)
OnKeyDown (forms) TabStop (forms)
OnKeyPress (forms) Tag
OnKeyUp (forms) Top
OnLostFocus (forms) ValidationRule (forms)
OnMouseDown (forms) ValidationText (forms)
OnMouseMove (forms) Visible
OnMouseUp (forms) Width
PROPERTY - ProjectName
You can use the ProjectName property to specify or determine the name of your Microsoft
Access Application object.
Setting
The ProjectName property is a string expression that's the name of your Microsoft Access
Application object. You can't set the ProjectName property to the name of an existing class
of objects, for example, "application," "form," or "report". If you convert a database with
a name that is the same as that of an existing class of objects, Microsoft Access will
append an underscore to the name to prevent naming conflicts. For example, if the database
you are converting is named "Application", the database will have a project name of
"Application_" in Microsoft Access 97.
You can set the ProjectName property from Tools menu -> Options ->
Options dialog -> Advanced tab, or by using the SetOption method in Visual Basic.
For example:
Application.SetOption "Project Name", "MyAccessProject"
Remarks
When you create a new database, Microsoft Access sets the ProjectName property to the
database file name without the ".mdb" extension. Changing the database file name has
no effect on the existing ProjectName property setting.
When you set the ProjectName property, the name of your Application object appears in the
References dialog box, available in the Module window by clicking References on the
Tools menu.
When you change the setting of the ProjectName property, your project will no longer be
in a compiled state. To recompile the project, you must close and reopen your database
and then click Compile And Save All Modules on the Debug menu.
From another application, such as Microsoft Excel, you can use the project name as part
of the fully qualified name of an item in a Microsoft Access project by using the syntax
projectname.Application.Forms!formname.
Example
to refer to the LastName field on the Employees form in the Northwind sample database
from Microsoft Excel, you set a reference to the Northwind database and then use the
following reference:
Dim strLstName As String
strLastName = Northwind.Application.Forms!Employees!LastName
You can create a reference to a Microsoft Access database from another application
(eg, Excel) by selecting the project name (the Application object) from the
application's Module window -> Tools menu -> References -> References dialog.
Once you select the project name, it also appears in the Project/Library list in the
Object Browser.
PROPERTY - RecordCount
Returns the number of records accessed in a Recordset object, or the total number of
records in a table-type Recordset or TableDef object.
Return Values
The return value is a Long data type.
Remarks
Use the RecordCount property to find out how many records in a Recordset or TableDef
object have been accessed. The RecordCount property doesn't indicate how many records
are contained in a dynaset-, snapshot-, or forward-only–type Recordset object until all
records have been accessed. Once the last record has been accessed, the RecordCount
property indicates the total number of undeleted records in the Recordset or TableDef
object. To force the last record to be accessed, use the MoveLast method on the Recordset
object. You can also use an SQL Count function to determine the approximate number of
records your query will return.
Note
Using the MoveLast method to populate a newly opened Recordset negatively impacts
performance. Unless it is necessary to have an accurate RecordCount as soon as you
open a Recordset, it's better to wait until you populate the Recordset with other
portions of code before checking the RecordCount property.
As your application deletes records in a dynaset-type Recordset object, the value of
the RecordCount property decreases. However, records deleted by other users aren't
reflected by the RecordCount property until the current record is positioned to a
deleted record. If you execute a transaction that affects the RecordCount property
setting and you subsequently roll back the transaction, the RecordCount property won't
reflect the actual number of remaining records.
The RecordCount property of a snapshot- or forward-only–type Recordset object isn't affected
by changes in the underlying tables.
A Recordset or TableDef object with no records has a RecordCount property setting of 0.
When you work with linked TableDef objects, the RecordCount property setting is always –1.
Using the Requery method on a Recordset object resets the RecordCount property just as
if the query were re-executed.
Example (DAO)
This example demonstrates the RecordCount property with different types of Recordsets
before and after they're populated.
Sub RecordCountX()
Dim dbsNorthwind As Database
Dim rstEmployees As Recordset
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
With dbsNorthwind
' Open table-type Recordset and show RecordCount property.
Set rstEmployees = .OpenRecordset("Employees")
Debug.Print "Table-type recordset from Employees table"
Debug.Print " RecordCount = " & rstEmployees.RecordCount
rstEmployees.Close
' Open dynaset-type Recordset and show RecordCount property before
' populating the Recordset.
Set rstEmployees = .OpenRecordset("Employees", _
dbOpenDynaset)
Debug.Print "Dynaset-type recordset " & _
"from Employees table before MoveLast"
Debug.Print " RecordCount = " & rstEmployees.RecordCount
' Show the RecordCount property after populating the Recordset.
rstEmployees.MoveLast
Debug.Print "Dynaset-type recordset " & _
"from Employees table after MoveLast"
Debug.Print " RecordCount = " & rstEmployees.RecordCount
rstEmployees.Close
' Open snapshot-type Recordset and show RecordCount property
' before populating the Recordset.
Set rstEmployees = .OpenRecordset("Employees", dbOpenSnapshot)
Debug.Print "Snapshot-type recordset " & _
"from Employees table before MoveLast"
Debug.Print " RecordCount = " & rstEmployees.RecordCount
' Show the RecordCount property after populating the Recordset.
rstEmployees.MoveLast
Debug.Print "Snapshot-type recordset " & _
"from Employees table after MoveLast"
Debug.Print " RecordCount = " & rstEmployees.RecordCount
rstEmployees.Close
' Open forward-only-type Recordset and show RecordCount property
' before populating the Recordset.
Set rstEmployees = .OpenRecordset("Employees", _
dbOpenForwardOnly)
Debug.Print "Forward-only-type recordset " & _
"from Employees table before MoveLast"
Debug.Print " RecordCount = " & rstEmployees.RecordCount
' Show the RecordCount property after calling the MoveNext method.
rstEmployees.MoveNext
Debug.Print "Forward-only-type recordset " & _
"from Employees table after MoveNext"
Debug.Print " RecordCount = " & rstEmployees.RecordCount
rstEmployees.Close
.Close
End With
End Sub
Example (Access)
The following example creates a Recordset object based on the Orders table and then
determines the number of records in the Recordset object:
Sub CountRecords()
Dim dbs As Database, rst As Recordset
' Return reference to current database.
Set dbs = CurrentDb
' Open table-type Recordset object.
Set rst = dbs.OpenRecordset("Orders")
Debug.Print rst.RecordCount
rst.Close
Set dbs = Nothing
End Sub
Example (Excel)
This example displays the number of records in the Customer recordset in the Nwindex.mdb
database.
To create the Nwindex.mdb database, run the Microsoft Excel example for the CreateDatabase
method.
Dim db As Database, rs As Recordset
Set db = Workspaces(0).OpenDatabase(Application.Path & "\NWINDEX.MDB")
Set rs = db.OpenRecordset("Customer")
On Error GoTo errorHandler
rs.MoveLast
MsgBox "There are " & rs.RecordCount & " records in " & rs.Name
rs.Close
db.Close
Exit Sub
errorHandler:
MsgBox "There are no records in " & rs.Name
rs.Close
db.Close
PROPERTY - Selected
You can use the Selected property in Visual Basic to determine if an item in a list
box is selected.
Setting
The Selected property is a zero-based array that contains the selected state of each
item in a list box.
Setting Description
True (–1) The list box item is selected.
False (0) The list box item isn't selected.
You can get or set the Selected property by using Visual Basic.
This property is available only at run time.
Remarks
When a list box control's MultiSelect property is set to None, only one item can have
its Selected property set to True. When a list box control's MultiSelect property is set
to Simple or Extended, any or all of the items can have their Selected property set to
True. A multiple-selection list box bound to a field will always have a Value property
equal to Null. You use the Selected property or the ItemsSelected collection to retrieve
information about which items are selected.
You can use the Selected property to select items in a list box by using Visual Basic.
For example, the following expression selects the fifth item in the list:
Me!Listbox.Selected(4) = True
Property - Text
You can use the Text property to set or return the text contained in a text box or in the
text box portion of a combo box.
Setting
You can set the Text property to the text you want to display in the control. You can also
use the Text property to read the text currently in the control.
You can set or read this property only by using a macro or Visual Basic.
Note
To set or return a control's Text property, the control must have the focus, or an error
occurs. To move the focus to a control, you can use the SetFocus method or GoToControl
action.
Remarks
While the control has the focus, the Text property contains the text data currently in the
control; the Value property contains the last saved data for the control. When you move the
focus to another control, the control's data is updated, and the Value property is set to
this new value. The Text property setting is then unavailable until the control gets the focus
again. If you use the Save Record command on the Records menu to save the data in the control
without moving the focus, the Text property and Value property settings will be the same.
Example
The following example uses the Text property to enable a Next button named btnNext whenever
the user enters text into a text box named txtName. Anytime the text box is empty, the Next
button is disabled.
Sub txtName_Change()
btnNext.Enabled = Len(Me!txtName.Text & "")<>0
End Sub
PROPERTY - Type (DAO)
Sets or returns a value that indicates the operational type or data type of an object.
Settings and Return Values
The setting or return value is a constant that indicates an operational or data type.
For a Field or Property object, this property is read/write until the object is appended
to a collection or to another object, after which it's read-only. For a QueryDef, Recordset,
or Workspace object, the property setting is read-only. For a Parameter object in a Microsoft
Jet workspace the property is read-only, while in an ODBCDirect workspace the property is
always read-write.
For a Field, Parameter, or Property object, the possible settings and return values are
described in the following table.
Constant Description
dbBigInt Big Integer
dbBinary Binary
dbBoolean Boolean
dbByte Byte
dbChar Char
dbCurrency Currency
dbDate Date/Time
dbDecimal Decimal
dbDouble Double
dbFloat Float
dbGUID GUID
dbInteger Integer
dbLong Long
dbLongBinary Long Binary (OLE Object)
dbMemo Memo
dbNumeric Numeric
dbSingle Single
dbText Text
dbTime Time
dbTimeStamp Time Stamp
dbVarBinary VarBinary
For a QueryDef object, the possible settings and return values are shown in the
following table.
Constant Query type
dbQAction Action
dbQAppend Append
dbQCompound Compound
dbQCrosstab Crosstab
dbQDDL Data-definition
dbQDelete Delete
dbQMakeTable Make-table
dbQProcedure Procedure (ODBCDirect workspaces only)
dbQSelect Select
dbQSetOperation Union
dbQSPTBulk Used with dbQSQLPassThrough to specify a query that doesn't
return records (Microsoft Jet workspaces only).
dbQSQLPassThrough Pass-through (Microsoft Jet workspaces only)
dbQUpdate Update
Note
To create an SQL pass-through query in a Microsoft Jet workspace, you don't need to
explicitly set the Type property to dbQSQLPassThrough. The Microsoft Jet database engine
automatically sets this when you create a QueryDef object and set the Connect property.
For a Recordset object, the possible settings and return values are as follows.
Constant Recordset type
dbOpenTable Table (Microsoft Jet workspaces only)
dbOpenDynamic Dynamic (ODBCDirect workspaces only)
dbOpenDynaset Dynaset
dbOpenSnapshot Snapshot
dbOpenForwardOnly Forward-only
For a Workspace object, the possible settings and return values are as follows.
Constant Workspace type
dbUseJet The Workspace is connected to the Microsoft Jet database engine.
dbUseODBC The Workspace is connected to an ODBC data source.
Remarks
When you append a new Field, Parameter, or Property object to the collection of an
Index, QueryDef, Recordset, or TableDef object, an error occurs if the underlying
database doesn't support the data type specified for the new object.
Example (DAO)
This example demonstrates the Type property by returning the name of the constant
corresponding to the value of the Type property of four different Recordsets. The
RecordsetType function is required for this procedure to run.
Sub TypeX()
Dim dbsNorthwind As Database
Dim rstEmployees As Recordset
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
' Default is dbOpenTable.
Set rstEmployees = _
dbsNorthwind.OpenRecordset("Employees")
Debug.Print _
"Table-type recordset (Employees table): " & _
RecordsetType(rstEmployees.Type)
rstEmployees.Close
Set rstEmployees = _
dbsNorthwind.OpenRecordset("Employees", _
dbOpenDynaset)
Debug.Print _
"Dynaset-type recordset (Employees table): " & _
RecordsetType(rstEmployees.Type)
rstEmployees.Close
Set rstEmployees = _
dbsNorthwind.OpenRecordset("Employees", _
dbOpenSnapshot)
Debug.Print _
"Snapshot-type recordset (Employees table): " & _
RecordsetType(rstEmployees.Type)
rstEmployees.Close
Set rstEmployees = _
dbsNorthwind.OpenRecordset("Employees", _
dbOpenForwardOnly)
Debug.Print _
"Forward-only-type recordset (Employees table): " & _
RecordsetType(rstEmployees.Type)
rstEmployees.Close
dbsNorthwind.Close
End Sub
Function RecordsetType(intType As Integer) As String
Select Case intType
Case dbOpenTable
RecordsetType = "dbOpenTable"
Case dbOpenDynaset
RecordsetType = "dbOpenDynaset"
Case dbOpenSnapshot
RecordsetType = "dbOpenSnapshot"
Case dbOpenForwardOnly
RecordsetType = "dbOpenForwardOnly"
End Select
End Function
This example demonstrates the Type property by returning the name of the constant
corresponding to the value of the Type property of all the Field objects in the Employees
table. The FieldType function is required for this procedure to run.
Sub TypeX2()
Dim dbsNorthwind As Database
Dim fldLoop As Field
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
Debug.Print "Fields in Employees TableDef:"
Debug.Print " Type - Name"
' Enumerate Fields collection of Employees table.
For Each fldLoop In _
dbsNorthwind.TableDefs!Employees.Fields
Debug.Print " " & FieldType(fldLoop.Type) & _
" - " & fldLoop.Name
Next fldLoop
dbsNorthwind.Close
End Sub
Function FieldType(intType As Integer) As String
Select Case intType
Case dbBoolean
FieldType = "dbBoolean"
Case dbByte
FieldType = "dbByte"
Case dbInteger
FieldType = "dbInteger"
Case dbLong
FieldType = "dbLong"
Case dbCurrency
FieldType = "dbCurrency"
Case dbSingle
FieldType = "dbSingle"
Case dbDouble
FieldType = "dbDouble"
Case dbDate
FieldType = "dbDate"
Case dbText
FieldType = "dbText"
Case dbLongBinary
FieldType = "dbLongBinary"
Case dbMemo
FieldType = "dbMemo"
Case dbGUID
FieldType = "dbGUID"
End Select
End Function
This example demonstrates the Type property by returning the name of the constant
corresponding to the value of the Type property of all the QueryDef objects in Northwind.
The QueryDefType function is required for this procedure to run.
Sub TypeX3()
Dim dbsNorthwind As Database
Dim qdfLoop As QueryDef
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
Debug.Print "QueryDefs in Northwind Database:"
Debug.Print " Type - Name"
' Enumerate QueryDefs collection of Northwind database.
For Each qdfLoop In dbsNorthwind.QueryDefs
Debug.Print " " & _
QueryDefType(qdfLoop.Type) & " - " & qdfLoop.Name
Next qdfLoop
dbsNorthwind.Close
End Sub
Function QueryDefType(intType As Integer) As String
Select Case intType
Case dbQSelect
QueryDefType = "dbQSelect"
Case dbQAction
QueryDefType = "dbQAction"
Case dbQCrosstab
QueryDefType = "dbQCrosstab"
Case dbQDelete
QueryDefType = "dbQDelete"
Case dbQUpdate
QueryDefType = "dbQUpdate"
Case dbQAppend
QueryDefType = "dbQAppend"
Case dbQMakeTable
QueryDefType = "dbQMakeTable"
Case dbQDDL
QueryDefType = "dbQDDL"
Case dbQSQLPassThrough
QueryDefType = "dbQSQLPassThrough"
Case dbQSetOperation
QueryDefType = "dbQSetOperation"
Case dbQSPTBulk
QueryDefType = "dbQSPTBulk"
End Select
End Function
Example (Access)
The following example creates a new Field object and sets its Size and Type properties.
The procedure then appends the new object to the Fields collection of the Employees table
in the TableDefs collection of the database.
Sub NewField()
Dim dbs As Database, tdf As TableDef
Dim fld As Field
' Return reference to current database.
Set dbs = CurrentDb
' Return reference to Employees table.
Set tdf = dbs.TableDefs!Employees
' Create Field object.
Set fld = tdf.CreateField("DaysOfVacation")
' Set field properties.
fld.Type = dbText
fld.Size = 20
' Append fld to Fields collection.
tdf.Fields.Append fld
Set dbs = Nothing
End Sub
You can also use the CreateField method to set the Name, Type, and Size properties if
you provide name, type, and size as arguments.
Set fld = tdfEmployees.CreateField("DaysOfVacation", dbText, 20)
Example (Excel)
This example copies to Sheet1 all fields of the Double type from Orddtail.dbf, a dBASE IV
table located in the C:\Program Files\Common Files\Microsoft Shared\MSquery folder.
(In Windows NT, Orddtail.dbf is located in the C:\Windows\Msapps\Msquery folder.)
Dim db As Database, recordsToCopy As Recordset, tDef As Recordset
Dim fieldsToStore(1000), fileName As String
fileName = "ORDDTAIL.DBF"
Set db = _
Workspaces(0).OpenDatabase("C:\Program Files\Common Files\Microsoft Shared\MSquery", _
False, False, "dBASE IV")
Set tDef = db.OpenRecordset(fileName)
n = 0
Sheets("Sheet1").Activate
For i = 0 To tDef.Fields.Count - 1
If tDef.Fields(i).Type = dbDouble Then
fieldsToStore(n) = tDef.fields(i).Name
n = n + 1
End If
Next
If fieldsToStore(0) = "" Then
MsgBox "There are no number fields in this table."
Exit Sub
End If
For i = 0 To n - 1
records = "SELECT " & "[" & fieldsToStore(i) & "]" _
& " from " & db.Recordsets(fileName).Name & ";"
Set recordsToCopy = db.OpenRecordset(records)
With ActiveSheet.Cells(1, i + 1)
.CopyFromRecordset recordsToCopy
.ColumnWidth = recordsToCopy.fields(0).Size
End With
Next
recordsToCopy.Close
tDef.Close
db.Close
PROPERTY - Value
You can use the Value property to determine or specify if a control is selected, the
selected value or option within the control, or the text contained in a text box control.
Check box, option button, and toggle button controls. Determines or specifies whether or not the control is selected.
Combo box, list box, and option group controls. Determines or specifies which value or option in the control is selected.
Text box controls. Determines or specifies the text in the text box.
Tab control. Determines or specifies the selected Page object.
Setting
The Value property uses the following setting depending on the specified control.
Control Setting Description Visual Basic
Check box True The check box is selected.(Default) True (–1)
False The check box is cleared. False (0)
Combo box [The text This may or may not be the same as the setting
in the text for the Text property of the control. The
box portion current setting for the Text property is what
ofthe control] is displayed in the text box portion of the
combo box; the Value property is set to the
Text property setting only after this text
is saved.
List box [The list box The value in the bound column for the
item value] item selected in the list.
Option button True The option button is selected.(Default) True
False The option button isn't selected. False
Option group [The The OptionValue property setting for
OptionValue the selected control in the group.
property
setting]
Text box [The value of The Text property returns the formatted
the control's string. The Text property may be different
Text property] than the Value property for a text box
control. The Text property is the current
contents of the control. The Value property
is the saved value of the text box control.
The Text property is always current while
the control has the focus.
Toggle button True The toggle button is pressed in.The toggle True
False button isn't pressed in. False
Tab control [An Integer The Value property of a tab control contains
value the index number of the current Page object.
representing There is one Page object for each tab in a
the index tab control. The first Page object always
number of the has an index number of 0, the second has an
currently index number of 1, and so on.
selected Page
object]
Bound object The Value property for a bound object frame or
frame or chart a bound chart control is set to the value of
control the field that the control is bound to. Since
these fields normally contain OLE objects or
chart objects, which are stored as binary data,
this value is usually meaningless.
ActiveX control Some ActiveX controls support the Value property.
For example, the Value property setting for a
Calendar control is the currently selected date
in the control. For more information, see the
documentation for each ActiveX control.
You can set this property by using a macro or Visual Basic.
Remarks
The Value property returns or sets a control's default property, which is the property that
is assumed when you don't explicitly specify a property name. In the following example,
because the default value of the text box is the value of the Text property, you can refer
to its Text property setting without explicitly specifying the name of the property.
Forms!frmCustomers!txtLastName = "Smith"
This means that the following two statements are equivalent.
Forms!frmCustomers!optCreditApproved.Value = True
Forms!frmCustomers!optCreditApproved = True
Note The Value property is not the same as the DefaultValue property, which specifies the
value that a property is assigned when a new record is created.
Example
The following example shows how you can call one of two procedures, depending whether the
Credit check box on the Customers form is selected or cleared.
Sub PaymentType()
If Forms!Customers!Credit.Value = False Then
ProcessCash
ElseIf Forms!Customers!Credit.Value = True Then
ProcessCredit
End If
End Sub
RECORDSET - Dynaset-type
A dynaset-type Recordset object is a dynamic set of records that can contain fields from
one or more tables or queries in a database and may be updatable. In an ODBCDirect
database, a dynaset-type Recordset object corresponds to an ODBC keyset cursor.
Remarks
A dynaset-type Recordset object is a type of Recordset object you can use to manipulate
data in an underlying database table or tables.
It differs from a snapshot-type Recordset object because the dynaset stores only the primary
key for each record, instead of actual data. As a result, a dynaset is updated with changes
made to the source data, while the snapshot is not. Like the table-type Recordset object, a
dynaset retrieves the full record only when it's needed for editing or display purposes.
To create a dynaset-type Recordset object, use the OpenRecordset method on an open database,
against another dynaset- or snapshot-type Recordset object, on a QueryDef object, or on a
TableDef object. (Opening Recordset objects on other Recordset objects or TableDef objects
is available only in Microsoft Jet workspaces.)
If you request a dynaset-type Recordset object and the Microsoft Jet database engine can't
gain read/write access to the records, the Microsoft Jet database engine may create a
read-only, dynaset-type Recordset object.
As users update data, the base tables reflects these changes. Therefore, current data is
available to your application when you reposition the current record. In a multiuser
database, more than one user can open a dynaset-type Recordset object referring to the
same records. Because a dynaset-type Recordset object is dynamic, when one user changes a
record, other users have immediate access to the changed data. However, if one user adds
a record, other users won’t see the new record until they use the Requery method on the
Recordset object. If a user deletes a record, other users are notified when they try to
access it.
Records added to the database don't become a part of your dynaset-type Recordset object
unless you add them by using the AddNew and Update methods. For example, if you use an
action query containing an INSERT INTO SQL statement to add records, the new records aren't
included in your dynaset-type Recordset object until you either use the Requery method or
you rebuild your Recordset object using the OpenRecordset method.
To maintain data integrity, the Microsoft Jet database engine can lock dynaset- and
table-type Recordset objects during Edit (pessimistic locking) or Update operations
(optimistic locking) so that only one user can update a particular record at a time.
When the Microsoft Jet database engine locks a record, it locks the entire 2K page
containing the record.
You can also use optimistic and pessimistic locking with non-ODBC tables. When you access
external tables using ODBC through a Microsoft Jet workspace, you should always use
optimistic locking. The LockEdits property and the lockedits parameter of the OpenRecordset
method determine the locking conditions during editing.
Not all fields can be updated in all dynaset-type Recordset objects. To determine whether you
can update a particular field, check the DataUpdatable property setting of the Field object.
A dynaset-type Recordset object may not be updatable if:
· There isn't a unique index on the ODBC or Paradox table or tables.
· The data page is locked by another user.
· The record has changed since you last read it.
· The user doesn't have permission.
· One or more of the tables or fields are read-only.
· The database is opened as read-only.
· The Recordset object was either created from multiple tables without a JOIN
statement or the query was too complex.
The order of a dynaset-type Recordset object or Recordset data doesn't necessarily follow
any specific sequence. If you need to order your data, use an SQL statement with an ORDER BY
clause to create the Recordset object. You can also use a WHERE clause to filter the records
so that only certain records are added to the Recordset object. Using SQL statements in this
way to select a subset of records and order them usually results in faster access to your
data than using the Filter and Sort properties.
Example (DAO)
This example opens a dynaset-type Recordset and shows the extent to which its fields
are updatable.
Sub dbOpenDynasetX()
Dim dbsNorthwind As Database
Dim rstInvoices As Recordset
Dim fldLoop As Field
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
Set rstInvoices = _
dbsNorthwind.OpenRecordset("Invoices", dbOpenDynaset)
With rstInvoices
Debug.Print "Dynaset-type recordset: " & .Name
If .Updatable Then
Debug.Print " Updatable fields:"
' Enumerate Fields collection of dynaset-type
' Recordset object, print only updatable
' fields.
For Each fldLoop In .Fields
If fldLoop.DataUpdatable Then
Debug.Print " " & fldLoop.Name
End If
Next fldLoop
End If
.Close
End With
dbsNorthwind.Close
End Sub
Example (Access)
The following example creates a dynaset-type Recordset object, then checks the Updatable
property of the Recordset object:
Sub RecentHires()
Dim dbs As Database, rst As Recordset
Dim strSQL As String
' Return reference to current database.
Set dbs = CurrentDb
' Open recordset on Employees table.
Set rst = dbs.OpenRecordset("Employees", dbOpenDynaset)
Debug.Print rst.Updatable
rst.Close
Set dbs = Nothing
End Sub
RECORDSET - Snapshot-type
A snapshot-type Recordset object is a static set of records that you can use to examine
data in an underlying table or tables. In an ODBCDirect database, a snapshot-type Recordset
object corresponds to a static cursor.
Remarks
To create a snapshot-type Recordset object, use the OpenRecordset method on an open
database, on another dynaset- or snapshot-type Recordset object, or on a QueryDef object.
A snapshot-type Recordset object can contain fields from one or more tables in a database.
In a Microsoft Jet workspace, a snapshot can't be updated. In an ODBCDirect workspace, a
snapshot may be updatable, depending on the ODBC driver.
When you create a snapshot-type Recordset object, data values for all fields (except Memo
and OLE Object (Long Binary) field data types in .mdb files) are brought into memory. Once
loaded, changes made to base table data aren't reflected in the snapshot-type Recordset
object data. To reload the snapshot-type Recordset object with current data, use the
Requery method, or re-execute the OpenRecordset method.
The order of snapshot-type Recordset object data doesn't necessarily follow any specific
sequence. To order your data, use an SQL statement with an ORDER BY clause to create the
Recordset object. You can also use this technique to filter the records so that only certain
records are added to the Recordset object. Using this technique instead of using the Filter
or Sort properties or testing each record individually generally results in faster access
to your data.
Snapshot-type Recordset objects are generally faster to create and access than dynaset-type
Recordset objects because their records are either in memory or stored in TEMP disk space,
and the Microsoft Jet database engine doesn't need to lock pages or handle multiuser issues.
However, snapshot-type Recordset objects use more resources than dynaset-type Recordset
objects because the entire record is downloaded to local memory.
Example (DAO)
This example opens a snapshot-type Recordset and demonstrates its read-only characteristics.
Sub dbOpenSnapshotX()
Dim dbsNorthwind As Database
Dim rstEmployees As Recordset
Dim prpLoop As Property
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
Set rstEmployees = _
dbsNorthwind.OpenRecordset("Employees", _
dbOpenSnapshot)
With rstEmployees
Debug.Print "Snapshot-type recordset: " & _
.Name
' Enumerate the Properties collection of the
' snapshot-type Recordset object, trapping for
' any properties whose values are invalid in
' this context.
For Each prpLoop In .Properties
On Error Resume Next
Debug.Print " " & _
prpLoop.Name & " = " & prpLoop
On Error Goto 0
Next prpLoop
.Close
End With
dbsNorthwind.Close
End Sub
Example (Access)
The following example creates a snapshot-type Recordset object from an SQL statement,
then prints the value of the Updatable property for the Recordset object. Since
snapshot-type Recordset objects are never updatable, the value of this property will
always be False (0).
Sub LongTermEmployees()
Dim dbs As Database, qdf As QueryDef, rst As Recordset
Dim strSQL As String
' Return reference to current database.
Set dbs = CurrentDb
' Construct SQL string.
strSQL = "SELECT * FROM Employees WHERE HireDate <= #1-1-94#;"
' Open snapshot-type Recordset object.
Set rst = dbs.OpenRecordset(strSQL, dbOpenSnapshot)
Debug.Print rst.Updatable
rst.Close
Set dbs = Nothing
End Sub
RECORDSET - Table-type
A table-type Recordset object represents a base table you can use to add, change, or delete
records from a table. Only the current record is loaded into memory. A predefined index
determines the order of the records in the Recordset object (Microsoft Jet workspaces only).
Remarks
To create a table-type Recordset object, use the OpenRecordset method on an open Database
object.
You can create a table-type Recordset object from a base table of a Microsoft Jet database,
but not from an ODBC or linked table. You can use the table-type Recordset object with
ISAM databases (like FoxPro, dBASE, or Paradox) when you open them directly.
Unlike dynaset- or snapshot-type Recordset objects, the table-type Recordset object can't
refer to more than one base table, and you can't create it with an SQL statement that
filters or sorts the data. Generally, when you access a table-type Recordset object, you
specify one of the predefined indexes for the table, which orders the data returned to your
application. If the table doesn't have an index, the data won't necessarily be in a
particular order. If necessary, your application can create an index that returns records
in a specific order. To choose a specific order for your table-type Recordset object, set
the Index property to a valid index.
Also unlike dynaset- or snapshot-type Recordset objects, you don't need to explicitly
populate table-type Recordset objects to obtain an accurate value for the RecordCount
property.
To maintain data integrity, table-type Recordset objects are locked during the Edit and
Update methods operations so that only one user can update a particular record at a time.
When the Microsoft Jet database engine locks a record, it locks the entire 2K page
containing the record.
Two kinds of locking are used with non-ODBC tables — pessimistic and optimistic.
ODBC-accessed tables always use optimistic locking. The LockEdits property determines
the locking conditions in effect during editing.
Example (DAO)
This example opens a table-type Recordset, sets its Index property, and enumerates
its records.
Sub dbOpenTableX()
Dim dbsNorthwind As Database
Dim rstEmployees As Recordset
Set dbsNorthwind = OpenDatabase("Northwind.mdb")
' dbOpenTable is default.
Set rstEmployees = _
dbsNorthwind.OpenRecordset("Employees")
With rstEmployees
Debug.Print "Table-type recordset: " & .Name
' Use predefined index.
.Index = "LastName"
Debug.Print " Index = " & .Index
' Enumerate records.
Do While Not .EOF
Debug.Print " " & !LastName & ", " & _
!FirstName
.MoveNext
Loop
.Close
End With
dbsNorthwind.Close
End Sub
Example (Access)
The following example opens a table-type Recordset object, then finds a specified record:
Sub FindEmployee()
Dim dbs As Database, tdf As TableDef
Dim rst As Recordset, idx As Index
Dim fldLastName As Field, fldFirstName As Field
' Return reference to current database.
Set dbs = CurrentDb
' Return reference to Employees table.
Set tdf = dbs.TableDefs!Employees
' Create new index.
Set idx = tdf.CreateIndex("FullName")
' Create and append index fields.
Set fldLastName = idx.CreateField("LastName", dbText)
Set fldFirstName = idx.CreateField("FirstName", dbText)
idx.Fields.Append fldLastName
idx.Fields.Append fldFirstName
' Append Index object.
tdf.Indexes.Append idx
' Open table-type Recordset object.
Set rst = dbs.OpenRecordset("Employees")
' Set current index to new index.
rst.Index = idx.Name
' Specify record to find.
rst.Seek "=", "Fuller", "Andrew"
If rst.NoMatch Then
Debug.Print "Seek failed."
Else
Debug.Print "Seek successful."
End If
rst.close
Set dbs = Nothing
End Sub
REFERENCES - Set to Type Libraries
When you set a reference to another application's type library, you can use the objects
supplied by that application in your code. For example, if you set a reference from Microsoft
Access to the Microsoft Excel library, you can then use Microsoft Excel objects through
Automation. If you set a reference to a Visual Basic project in another Microsoft Access
database, you can call its public procedures. If you set a reference to an ActiveX control,
you can use that control on Microsoft Access forms.
You can set a reference from Microsoft Access while the Module window is open, or you can
set a reference in Visual Basic code.
Setting a Reference from Microsoft Access
To set a reference to an application's type library:
1. On the Tools menu, click References. The References command on the Tools menu is available
only when a Module window is open and active in Design view.
2. Select the check boxes for those applications whose type libraries you want to reference.
Setting a Reference from Visual Basic
To set a reference from Visual Basic, you create a new Reference object representing the
desired reference. The References collection contains all currently set references.
To create a new Reference object, use either the AddFromFile or AddFromGUID method of the
References collection. To remove a Reference object, use the Remove method.
Advantages of Setting References
Your Automation code will run faster if you set a reference to another application's type
library before you work with its objects. If you've set a reference, you can declare an
object variable representing an object in the other application as its most specific type.
For example, if you're writing code to work with Microsoft Excel objects, you can declare
an object variable of type Excel.Application by using the following syntax only if you've
created a reference to the Microsoft Excel type library:
Dim appXL As New Excel.Application
If you haven't set a reference to the Microsoft Excel type library, you must declare the
variable as a generic variable of type Object. The following code runs more slowly:
Dim appXL As Object
Additionally, if you set a reference to an application's type library, all of its objects,
as well as their methods and properties, are listed in the Object Browser. This makes it
easy to determine what properties and methods are available to each object.
Since Microsoft Access is an ActiveX component that supports Automation, you can also set a
reference to its type library from another application and work with Microsoft Access objects
from that application.
SQL - Action Query
What is an action query and when would you use one?
An action query is a query that makes changes to many records in just one operation.
There are four types of action queries: delete, update, append, and make-table.
Delete query
Deletes a group of records from one or more tables. For example, you could use a delete
query to remove products that are discontinued or for which there are no orders. With
delete queries, you always delete entire records, not just selected fields within records.
Update query
Makes global changes to a group of records in one or more tables. For example, you can
raise prices by 10 percent for all dairy products, or you can raise salaries by 5 percent
for the people within a certain job category. With an update query, you can change data
in existing tables.
Append query
Adds a group of records from one or more tables to the end of one or more tables. For
example, suppose that you acquire some new customers and a database containing a table
of information on those customers. To avoid typing all this information in, you'd like
to append it to your Customers table. Append queries are also helpful for:
· Appending fields based on criteria. For example, you might want to append only the
names and addresses of customers with outstanding orders.
· Appending records when some of the fields in one table don't exist in the other table.
For example, in the Northwind sample database, the Customers table has 11 fields. Suppose
that you want to append records from another table that has fields that match 9 of the 11
fields in the Customers table. An append query will append the data in the matching fields
and ignore the others.
Make-table query
Creates a new table from all or part of the data in one or more tables. Make-table
queries are helpful for:
· Creating a table to export to other Microsoft Access databases. For example, you might
want to create a table that contains several fields from your Employees table, and then
export that table to a database used by your personnel department.
· Creating reports that display data from a specified point in time. For example, suppose
you want to print a report on 15-May-96 that displays the first quarter's sales totals
based on the data that was in the underlying tables as of 9:00 A.M. on 1-Apr-96. A report
based on a query or SQL statement extracts the most up-to-date data from the tables (the
data as of 15-May-96), rather than the records as of a specific date and time. To preserve
the data exactly as it was at 9:00 A.M. on 1-Apr-96 , create a make-table query at that
point in time to retrieve the records you need and store them in a new table. Then use this
table, rather than a query, as the basis for the reports.
· Making a backup copy of a table.
· Creating a history table that contains old records. For example, you could create a table
that stores all your old orders before deleting them from your current Orders table.
· Improving performance of forms and reports based on multiple-table queries or SQL
statements. For example, suppose you want to print multiple reports that are based on
a five-table query that includes totals. You may be able to speed things up by first
creating a make-table query that retrieves the records you need and stores them in one
table. Then you can base the reports on this table or specify the table in an SQL
statement as the record source for a form or report, so you don't have to rerun the
query for each report. However, the data in the table is frozen at the time you run the
make-table query.
SQL - Append Query
Append records from one table to another table using an append query
1 Create a query that contains the table whose records you want to append to another table.
2 In query Design view, click the arrow next to Query Type on the toolbar, and then
click Append. The Append dialog box appears.
3 In the Table Name box, enter the name of the table to append records to.
4 Click Current Database if the table is in the currently open database. Or click
Another Database and type the name (and path if necessary) of the database where the
table is stored.
You can also enter a path to a Microsoft FoxPro, Paradox, or dBASE database, or a
connection string to an SQL database.
5 Click OK.
6 Drag from the field list to the query design grid the fields you want to append and any
fields you want to use for setting criteria. Also, you may or may not want to add the primary
key field if it has an AutoNumber data type.
If all the fields in both tables have the same names, you can just drag the asterisk (*) to
the query design grid. However, if you're working in a database replica, you'll need to add
7 If the fields you've selected have the same name in both tables, Microsoft Access
automatically fills the matching name in the Append To row. If the fields in the two
tables don't have the same name, in the Append To row, enter the names of the fields
in the table you're appending to.
8 In the Criteria cell for the fields that you have dragged to the grid, type the criteria
on which additions will be made.
9 To preview the records that the query will append, click View on the toolbar. To
return to query Design view, click View on the toolbar again. Make any changes you want in Design view.
10 Click Run on the toolbar to add the records.
Note
To stop a query after you start it, press CTRL+BREAK.
SQL - Array as Query Destination
(from Vb6 Help: Chapter 12: Adding Queries and Reports
using Index search - "queries, collecting user input with")
Use the INTO clause of the SELECT - SQL statement to specify a destination.
The following example shows an INTO clause for an array:
SELECT * ;
FROM tastrade!customer ;
WHERE customer.country = "Canada" ;
INTO ARRAY aMyArray
SQL - Copy a Table Structure
to Copy a table structure to another table, use the following query:
SELECT *
INTO my_new_table
FROM my_old_table
WHERE 1=2
Note that the WHERE statement 1=2 is always false, so no data meets this criterion.
SQL - CONSTRAINT CLAUSE
A constraint is similar to an index, although it can also be used to establish a
relationship with another table.
You use the CONSTRAINT clause in ALTER TABLE and CREATE TABLE statements to create or
delete constraints. There are two types of CONSTRAINT clauses: one for creating a constraint
on a single field and one for creating a constraint on more than one field.
Note
When using non-Jet databases, the Jet engine doesn't support the use of CONSTRAINT, or any
of the data definition language (DDL) statements. Use the DAO Create methods instead.
Syntax
Single-field constraint:
CONSTRAINT name {PRIMARY KEY | UNIQUE | NOT NULL |
REFERENCES foreigntable [(foreignfield1, foreignfield2)]}
Multiple-field constraint: (ELAnote: join FOREIGN KEY & REFERENCES lines)
CONSTRAINT name
{PRIMARY KEY (primary1[, primary2 [, ...]]) |
UNIQUE (unique1[, unique2 [, ...]]) |
NOT NULL (notnull1[, notnull2 [, ...]]) |
FOREIGN KEY (ref1[, ref2 [, ...]])
REFERENCES foreigntable [(foreignfield1 [, foreignfield2 [, ...]])]}
The CONSTRAINT clause has these parts:
Part Description
name The name of the constraint to be created.
primary1, primary2 The name of the field or fields to be designated the
primary key.
unique1, unique2 The name of the field or fields to be designated as a
unique key.
notnull1, notnull2 The name of the field or fields that are restricted to
non-Null values.
ref1, ref2 The name of a foreign key field or fields that refer
to fields in another table.
foreigntable The name of the foreign table containing the field or
fields specified by foreignfield.
foreignfield1, foreignfield2 The name of the field or fields in foreigntable specified
by ref1, ref2. You can omit this clause if the referenced
field is the primary key of foreigntable.
Remarks
You use the syntax for a single-field constraint in the field-definition clause of an
ALTER TABLE or CREATE TABLE statement immediately following the specification of the
field's data type.
You use the syntax for a multiple-field constraint whenever you use the reserved word
CONSTRAINT outside a field-definition clause in an ALTER TABLE or CREATE TABLE statement.
Using CONSTRAINT, you can designate a field as one of the following types of constraints:
· You can use the UNIQUE reserved word to designate a field as a unique key. This means
that no two records in the table can have the same value in this field. You can constrain
any field or list of fields as unique. If a multiple-field constraint is designated as a
unique key, the combined values of all fields in the index must be unique, even if two or
more records have the same value in just one of the fields.
· You can use the PRIMARY KEY reserved words to designate one field or set of fields in a
table as a primary key. All values in the primary key must be unique and not Null, and there
can be only one primary key for a table.
Note
Don't set a PRIMARY KEY constraint on a table that already has a primary key; if you do,
an error occurs.
· You can use the FOREIGN KEY reserved words to designate a field as a foreign key. If the
foreign table's primary key consists of more than one field, you must use a multiple-field
constraint definition, listing all of the referencing fields, the name of the foreign table,
and the names of the referenced fields in the foreign table in the same order that the
referencing fields are listed. If the referenced field or fields are the foreign table's
primary key, you don't have to specify the referenced fields — by default, the database
engine behaves as if the foreign table's primary key is the referenced fields.
Examples (DAO)
This example creates a new table called ThisTable with two Text fields.
Sub CreateTableX1()
Dim dbs As Database
' Modify this line to include the path to Northwind
' on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Create a table with two text fields.
dbs.Execute "CREATE TABLE ThisTable " _
& "(FirstName TEXT, LastName TEXT);"
dbs.Close
End Sub
This example creates a new table called MyTable with two Text fields, a Date/Time field,
and a unique index made up of all three fields.
Sub CreateTableX2()
Dim dbs As Database
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Create a table with three fields and a unique index made up of all three fields.
dbs.Execute "CREATE TABLE MyTable " _
& "(FirstName TEXT, LastName TEXT, " _
& "DateOfBirth DATETIME, " _
& "CONSTRAINT MyTableConstraint UNIQUE " _
& "(FirstName, LastName, DateOfBirth));"
dbs.Close
End Sub
This example creates a new table with two Text fields and an Integer field. The SSN field
is the primary key.
Sub CreateTableX3()
Dim dbs As Database
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Create a table with three fields and a primary key.
dbs.Execute "CREATE TABLE NewTable " _
& "(FirstName TEXT, LastName TEXT, " _
& "SSN INTEGER CONSTRAINT MyFieldConstraint " _
& "PRIMARY KEY);"
dbs.Close
End Sub
Example (Access)
To try the following examples in Microsoft Access, first create a new query in the
Northwind sample database. Close the Show Table dialog box without specifying a table
or query. Switch to SQL view, paste an individual example into the SQL window, and run
the query.
Warning
These examples makes changes to the Northwind sample database. Before beginning, you may
wish to make a backup copy of the sample database.
The following example creates a new table with two Text fields:
CREATE TABLE FirstTable (FirstName TEXT, LastName TEXT);
The next example creates a new table with two Text fields, a Date/Time field, and a
unique index made up of all three fields:
CREATE TABLE SecondTable (FirstName TEXT,
LastName TEXT, DateOfBirth DATETIME,
CONSTRAINT MyTableConstraint UNIQUE (FirstName, LastName, DateOfBirth));
The following example creates a new table with two Text fields and an Integer Number field.
The SSN field is the primary key.
CREATE TABLE ThirdTable (FirstName TEXT, LastName TEXT, SSN INTEGER
CONSTRAINT MyFieldConstraint PRIMARY KEY);
SQL - CREATE INDEX STATEMENT
Creates a new index on an existing table.
Note
For non-Microsoft Jet databases, the Microsoft Jet database engine doesn't support the use
of CREATE INDEX (except to create a pseudo index on an ODBC linked table) or any of the data
definition language (DDL) statements. Use the DAO Create methods instead. For more
information, see the Remarks section.
Syntax
CREATE [ UNIQUE ] INDEX index
ON table (field [ASC|DESC][, field [ASC|DESC], ...])
[WITH { PRIMARY | DISALLOW NULL | IGNORE NULL }]
The CREATE INDEX statement has these parts:
Part Description
index The name of the index to be created.
table The name of the existing table that will contain the index.
field The name of the field or fields to be indexed. To create a single-field index, list
the field name in parentheses following the table name. To create a multiple-field
index, list the name of each field to be included in the index. To create descending
indexes, use the DESC reserved word; otherwise, indexes are assumed to be ascending.
Remarks
To prohibit duplicate values in the indexed field or fields of different records, use
UNIQUE reserved word.
In the optional WITH clause, you can enforce data validation rules. You can:
· Prohibit Null entries in the indexed field or fields of new records by using the
DISALLOW NULL option.
· Prevent records with Null values in the indexed field or fields from being included in
the index by using the IGNORE NULL option.
· Designate the indexed field or fields as the primary key by using the PRIMARY reserved
word. This implies that the key is unique, so you can omit the UNIQUE reserved word.
You can use CREATE INDEX to create a pseudo index on a linked table in an ODBC data source,
such as SQL Server, that does not already have an index. You don't need permission or access
to the remote server to create a pseudo index, and the remote database is unaware of and
unaffected by the pseudo index. You use the same syntax for both linked and native tables.
This can be especially useful to create an index on a table that would ordinarily be
read-only due to lack of an index.
You can also use the ALTER TABLE statement to add a single- or multiple-field index to a
table, and you can use the ALTER TABLE statement or the DROP statement to remove an index
created with ALTER TABLE or CREATE INDEX.
Note
Using a table that already has a primary key, don't try to create a new index on it with
the PRIMARY reserved word; this will cause an error.
Example (DAO)
This example creates an index consisting of the fields Home Phone and Extension in the
Employees table.
Sub CreateIndexX1()
Dim dbs As Database
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Create the NewIndex index on the Employees table.
dbs.Execute "CREATE INDEX NewIndex ON Employees " _
& "(HomePhone, Extension);"
dbs.Close
End Sub
This example creates an index on the Customers table using the CustomerID field. No two
records can have the same data in the CustomerID field, and no Null values are allowed.
Sub CreateIndexX2()
Dim dbs As Database
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Create a unique index, CustID, on the CustomerID field.
dbs.Execute "CREATE UNIQUE INDEX CustID " _
& "ON Customers (CustomerID) " _
& "WITH DISALLOW NULL;"
dbs.Close
End Sub
Example (Access)
To try the following examples in Microsoft Access, first create a new query in the
Northwind sample database. Close the Show Table dialog box without specifying a table
or query. Switch to SQL view, paste an individual example into the SQL window, and run
the query.
Warning
These examples makes changes to the Northwind sample database. Before beginning, you may
wish to make a backup copy of the sample database.
The next example creates an index consisting of the fields HomePhone and Extension in
the Employees table:
CREATE INDEX NewIndex ON Employees (HomePhone, Extension);
The following example creates an index on the Customers table with the CustomerID field.
No two records can have the same data in the CustomerID field, and no Null values are allowed.
CREATE UNIQUE INDEX CustID ON Customers (CustomerID) WITH DISALLOW NULL;
To delete the index created in the preceding example, you must use the DROP statement.
You can't delete the index from table Design view unless you also delete the relationship
on the Customers table. The following statement deletes the new index by using the DROP
statement:
DROP INDEX CustID ON Customers;
The following example creates an index on an ODBC linked table. The table's remote
database is unaware of and unaffected by the new index. The following example won't
work if you simply paste it into Microsoft Access; you first need to create an ODBC
linked table called OrderDetailsODBC.
CREATE UNIQUE INDEX OrderID ON OrderDetailsODBC (OrderID);
SQL - CREATE TABLE STATEMENT
Creates a new table.
Note
When using with non-Jet databases, the Jet database engine doesn't support the use of
CREATE TABLE, or any of the DDL statements. Use the DAO Create methods instead.
Syntax (ELAnote: the following should be a continuous line)
CREATE TABLE table (field1 type [(size)] [NOT NULL] [index1]
[, field2 type [(size)] [NOT NULL] [index2] [, ...]]
[, CONSTRAINT multifieldindex [, ...]])
The CREATE TABLE statement has these parts:
Part Description
table The name of the table to be created.
field1, field2 The name of field or fields to be created in the new table. You must
create at least one field.
type The data type of field in the new table.
size The field size in characters (Text and Binary fields only).
index1, index2 A CONSTRAINT clause defining a single-field index. See the CONSTRAINT
clause topic for more information on how to create this index.
multifieldindex A CONSTRAINT clause defining a multiple-field index. See the CONSTRAINT
clause topic for more information on how to create this index.
Remarks
Use the CREATE TABLE statement to define a new table and its fields and field constraints.
If NOT NULL is specified for a field, then new records are required to have valid data in
that field.
A CONSTRAINT clause establishes various restrictions on a field, and can be used to establish
the primary key. You can also use the CREATE INDEX statement to create a primary key or
additional indexes on existing tables.
You can use NOT NULL on a single field, or within a named CONSTRAINT clause that applies to
either a single field or to a multiple-field named CONSTRAINT. However, you can apply the
NOT NULL restriction only once to a field, or a run-time error occurs.
Examples (DAO)
This example creates a new table called ThisTable with two Text fields.
Sub CreateTableX1()
Dim dbs As Database
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Create a table with two text fields.
dbs.Execute "CREATE TABLE ThisTable " _
& "(FirstName TEXT, LastName TEXT);"
dbs.Close
End Sub
This example creates a new table called MyTable with two Text fields, a Date/Time field,
and a unique index made up of all three fields.
Sub CreateTableX2()
Dim dbs As Database
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Create a table with three fields and a unique index made up of all three fields.
dbs.Execute "CREATE TABLE MyTable " _
& "(FirstName TEXT, LastName TEXT, " _
& "DateOfBirth DATETIME, " _
& "CONSTRAINT MyTableConstraint UNIQUE " _
& "(FirstName, LastName, DateOfBirth));"
dbs.Close
End Sub
This example creates a new table with two Text fields and an Integer field. The SSN field
is the primary key.
Sub CreateTableX3()
Dim dbs As Database
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Create a table with three fields and a primary key.
dbs.Execute "CREATE TABLE NewTable " _
& "(FirstName TEXT, LastName TEXT, " _
& "SSN INTEGER CONSTRAINT MyFieldConstraint " _
& "PRIMARY KEY);"
dbs.Close
End Sub
Example (Access)
To try the following examples in Microsoft Access, first create a new query in the
Northwind sample database. Close the Show Table dialog box without specifying a table
or query. Switch to SQL view, paste an individual example into the SQL window, and run
the query.
Warning
These examples makes changes to the Northwind sample database. Before beginning, you may
wish to make a backup copy of the sample database.
The following example creates a new table with two Text fields:
CREATE TABLE FirstTable (FirstName TEXT, LastName TEXT);
The next example creates a new table with two Text fields, a Date/Time field, and a
unique index made up of all three fields:
CREATE TABLE SecondTable (FirstName TEXT,
LastName TEXT, DateOfBirth DATETIME,
CONSTRAINT MyTableConstraint UNIQUE (FirstName, LastName, DateOfBirth));
The following example creates a new table with two Text fields and an Integer Number
field. The SSN field is the primary key.
CREATE TABLE ThirdTable (FirstName TEXT, LastName TEXT, SSN INTEGER
CONSTRAINT MyFieldConstraint PRIMARY KEY);
SQL - IN Clause
(
see also.. SQL IN Operator )
The following table shows how you can use the IN clause to retrieve data from an external
database. Each example assumes the Customers table is stored in an external database.
Note
The SQL IN clause is different than the SQL In operator, which is used to determine whether
the value of an expression is equal to any of several values in a specified list.
External database SQL statement
Microsoft Jet database. SELECT CustomerID
JetData.mdb is the name of the Jet FROM Customers
database that contains the Customers IN 'C:\My Documents\JetData.mdb'
table. WHERE CustomerID Like 'A*';
Microsoft Excel workbook (.xls file). SELECT CustomerID, CompanyName
XLData.xls is a Microsoft Excel FROM [Customers$]
workbook that contains a worksheet IN 'C:\My Documents\XLData.xls' 'EXCEL 5.0;'
called Customers. CustomersRange is WHERE CustomerID Like 'A*';
a named range in that worksheet. - or -
Note that to denote the entire SELECT CustomerID, CompanyName
worksheet as the table, you must FROM CustomersRange
append a dollar sign ($) and enclose IN 'C:\My Documents\XLData.xls' 'EXCEL 5.0;'
the name in brackets. WHERE CustomerID Like 'A*';
dBASE III or IV. SELECT CustomerID
To retrieve data from a dBASE III FROM Customers
table, substitute dBASE III for IN C:\DBASE\DATA\SALES dBASE IV;
dBASE IV. WHERE CustomerID Like A*;
dBASE III or IV (DATABASE syntax). SELECT CustomerID
To retrieve data from a dBASE III FROM Customers
table, substitute dBASE III for IN [dBASE IV;DATABASE=C:\DBASE\DATA\SALES;]
dBASE IV. ` WHERE CustomerID Like A*;
Paradox 3.x or 4.x. SELECT CustomerID
To retrieve data from a Paradox FROM Customers
version 3.x table, substitute IN C:\PARADOX\DATA\SALES Paradox 4.x;
Paradox 3.x for Paradox 4.x. WHERE CustomerID Like A*;
Paradox 3.x or 4.x (DATABASE syntax). SELECT CustomerID
To retrieve data from a Paradox FROM Customers
version 3.x table, substitute Paradox IN [Paradox 4.x;DATABASE=C:\PARADOX\DATA\SALES;]
3.x for Paradox 4.x. WHERE CustomerID Like A*;
SQL - In Operator
(
see also.. SQL IN Clause )
Determines whether the value of an expression is equal to any of several values in a
specified list.
Syntax
expr [Not] In(value1, value2, . . .)
Remarks
The In operator syntax has these parts:
Part Description
expr Expression identifying the field that contains the data you
want to evaluate.
value1, value2 Expression or list of expressions against which you want to
evaluate expr.
If expr is found in the list of values, the In operator returns True; otherwise, it
returns False. You can include the Not logical operator to evaluate the opposite condition
(that is, whether expr is not in the list of values).
Example
Use In to determine which orders are shipped to a set of specified regions:
SELECT *
FROM Orders
WHERE ShipRegion In ('Avon','Glos','Som')
Example (DAO)
The following example uses the Orders table in the Northwind.mdb database to create a
query that includes all orders shipped to Lancashire and Essex and the dates shipped.
This example calls the EnumFields procedure, which you can find in the SELECT statement
example.
Sub InX()
Dim dbs As Database, rst As Recordset
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Select records from the Orders table that have a ShipRegion value of Lancashire
' or Essex.
Set rst = dbs.OpenRecordset("SELECT " _
& "CustomerID, ShippedDate FROM Orders " _
& "WHERE ShipRegion In " _
& "('Lancashire','Essex');")
' Populate the Recordset.
rst.MoveLast
' Call EnumFields to print the contents of the Recordset.
EnumFields rst, 12
dbs.Close
End Sub
SQL - INSERT INTO STATEMENT
Adds a record or multiple records to a table. This is referred to as an append query.
Syntax
Multiple-record append query:
INSERT INTO target [IN externaldatabase] [(field1[, field2[, ...]])]
SELECT [source.]field1[, field2[, ...]
FROM tableexpression
Single-record append query:
INSERT INTO target [(field1[, field2[, ...]])]
VALUES (value1[, value2[, ...])
The INSERT INTO statement has these parts:
Part Description
target The name of the table or query to append records to.
externaldatabase The path to an external database. For a description of the path,
see the IN clause.
source The name of the table or query to copy records from.
field1, field2 Names of the fields to append data to, if following a target
argument, or the names of fields to obtain data from, if following
a source argument.
tableexpression The name of the table or tables from which records are inserted.
This argument can be a single table name or a compound resulting
from an INNER JOIN, LEFT JOIN, or RIGHT JOIN operation or a saved
query.
value1, value2 The values to insert into the specific fields of the new
record. Each value is inserted into the field that corresponds
to the value's position in the list: value1 is inserted into
field1 of the new record, value2 into field2, and so on. You
must separate values with a comma, and enclose text fields in
quotation marks (' ').
Remarks
You can use the INSERT INTO statement to add a single record to a table using the
single-record append query syntax as shown above. In this case, your code specifies
the name and value for each field of the record. You must specify each of the fields
of the record that a value is to be assigned to and a value for that field. When you
don't specify each field, the default value or Null is inserted for missing columns.
Records are added to the end of the table.
You can also use INSERT INTO to append a set of records from another table or query by
using the SELECT ... FROM clause as shown above in the multiple-record append query
syntax. In this case, the SELECT clause specifies the fields to append to the specified
target table.
The source or target table may specify a table or a query. If a query is specified,
the Microsoft Jet database engine appends records to any and all tables specified by
the query.
INSERT INTO is optional but when included, precedes the SELECT statement.
If your destination table contains a primary key, make sure you append unique, non-Null
values to the primary key field or fields; if you don't, the Microsoft Jet database
engine won't append the records.
If you append records to a table with an AutoNumber field and you want to renumber the
appended records, don't include the AutoNumber field in your query. Do include the
AutoNumber field in the query if you want to retain the original values from the field.
Use the IN clause to append records to a table in another database.
To create a new table, use the SELECT... INTO statement instead to create a make-table
query.
To find out which records will be appended before you run the append query, first
execute and view the results of a select query that uses the same selection criteria.
An append query copies records from one or more tables to another. The tables that
contain the records you append aren't affected by the append query.
Instead of appending existing records from another table, you can specify the value for
each field in a single new record using the VALUES clause. If you omit the field list,
the VALUES clause must include a value for every field in the table; otherwise, the
INSERT operation will fail. Use an additional INSERT INTO statement with a VALUES clause
for each additional record you want to create.
Example (Access)
To try the following example, create a copy of the Customers table and name it
NewCustomers. This example selects all records in the New Customers table and
adds them to the Customers table. When individual columns aren't designated, the
SELECT table column names must match exactly those in the INSERT INTO table.
INSERT INTO Customers SELECT * FROM NewCustomers;
The next example creates a new record in the Employees table:
INSERT INTO Employees (FirstName,LastName, Title) VALUES ('Harry', 'Washington', 'Trainee');
The following example selects all trainees from an assumed Trainees table who were hired
more than 30 days ago and adds their records to the Employees table.
INSERT INTO Employees SELECT Trainees.* FROM Trainees WHERE HireDate < Now() - 30;
You can use the INSERT INTO clause to back up information in your database before it is
changed. For example, you can back up information in an Employees table immediately
before a user makes any changes to the data in that table.
To try the following example, in the Database window copy the Employees table to a new
table called EmployeeHistory by clicking the table, clicking Copy on the toolbar,
then clicking Paste Under Paste Options in the Paste Table As dialog box, click
Structure Only. This will copy the structure of the table only, without any data. Next
paste the following SQL statement into a new query and save the query as BackUpQuery:
INSERT INTO EmployeesHistory (FirstName, LastName, Title)
VALUES (Forms!Employees!FirstName, Forms!Employees!Lastname,Forms!Employees!Title);
Open the Employees form in form Design view and set the form's BeforeUpdate property
to [Event Procedure]. In the BeforeUpdate event procedure, enter the following code:
DoCmd.OpenQuery "BackUpQuery"
Now the existing data in the Employees table will be copied to the backup table each
time a user changes it.
Example (DAO)
This example selects all records in a hypothetical New Customers table and adds them
to the Customers table. When individual columns are not designated, the SELECT table
column names must match exactly those in the INSERT INTO table.
Sub InsertIntoX1()
Dim dbs As Database
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Select all records in the New Customers table and add them to the Customers table.
dbs.Execute " INSERT INTO Customers " _
& "SELECT * " _
& "FROM [New Customers];"
dbs.Close
End Sub
This example creates a new record in the Employees table.
Sub InsertIntoX2()
Dim dbs As Database
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Create a new record in the Employees table. The first name is Harry, the last name
' is Washington, and the job title is Trainee.
dbs.Execute " INSERT INTO Employees " _
& "(FirstName,LastName, Title) VALUES " _
& "('Harry', 'Washington', 'Trainee');"
dbs.Close
End Sub
SQL - PARAMETERS Declaration
Declares the name and data type of each parameter in a parameter query.
Syntax
PARAMETERS name datatype [, name datatype [, ...]]
The PARAMETERS declaration has these parts:
Part Description
name The name of the parameter. Assigned to the Name property of the Parameter
object and used to identify this parameter in the Parameters collection.
You can use name as a string that is displayed in a dialog box while your
application runs the query. Use brackets ([ ]) to enclose text that contains
spaces or punctuation. For example, [Low price] and [Begin report with
which month?] are valid name arguments.
datatype One of the primary Microsoft Jet SQL data types or their synonyms.
Remarks
For queries that you run regularly, you can use a PARAMETERS declaration to create a
parameter query. A parameter query can help automate the process of changing query
criteria. With a parameter query, your code will need to provide the parameters each
time the query is run.
The PARAMETERS declaration is optional but when included precedes any other statement,
including SELECT.
If the declaration includes more than one parameter, separate them with commas. The
following example includes two parameters:
PARAMETERS [Low price] Currency, [Beginning date] DateTime;
You can use name but not datatype in a WHERE or HAVING clause. The following example
expects two parameters to be provided and then applies the criteria to records in the
Orders table:
PARAMETERS [Low price] Currency,
[Beginning date] DateTime;
SELECT OrderID, OrderAmount
FROM Orders
WHERE OrderAmount > [Low price]
AND OrderDate >= [Beginning date];
Example (DAO)
This example requires the user to provide a job title and then uses that job title as the
criteria for the query.
This example calls the EnumFields procedure, which you can find in the SELECT statement
example.
Sub ParametersX()
Dim dbs As Database, qdf As QueryDef
Dim rst As Recordset
Dim strSql As String, strParm As String
Dim strMessage As String
Dim intCommand As Integer
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("NorthWind.mdb")
' Define the parameters clause.
strParm = "PARAMETERS [Employee Title] TEXT; "
' Define an SQL statement with the parameters clause.
strSql = strParm & "SELECT LastName, FirstName, " _
& "EmployeeID " _
& "FROM Employees " _
& "WHERE Title =[Employee Title];"
' Create a QueryDef object based on the SQL statement.
Set qdf = dbs.CreateQueryDef("Find Employees", strSql)
Do While True
strMessage = "Find Employees by Job " _
& "title:" & Chr(13) _
& " Choose Job Title:" & Chr(13) _
& " 1 - Sales Manager" & Chr(13) _
& " 2 - Sales Representative" & Chr(13) _
& " 3 - Inside Sales Coordinator"
intCommand = Val(InputBox(strMessage))
Select Case intCommand
Case 1
qdf("Employee Title") = "Sales Manager"
Case 2
qdf("Employee Title") = "Sales Representative"
Case 3
qdf("Employee Title") = "Inside Sales Coordinator"
Case Else
Exit Do
End Select
' Create a temporary snapshot-type Recordset.
Set rst = qdf.OpenRecordset(dbOpenSnapshot)
' Populate the Recordset.
rst.MoveLast
' Call EnumFields to print the contents of the Recordset.
' Pass the Recordset object and desired field width.
EnumFields rst, 12
Loop
' Delete the QueryDef because this is a demonstration.
dbs.QueryDefs.Delete "Find Employees"
dbs.Close
End Sub
Example (Access)
To try the following examples in Microsoft Access, first create a new query in the
Northwind sample database. Close the Show Table dialog box without specifying a table
or query. Switch to SQL view, paste an individual example into the SQL window, and run
the query.
The following example prompts the user to provide an employee's last name and then uses
that entry as the criteria for the query:
PARAMETERS [Enter a Last Name:] Text;
SELECT *
FROM Employees
WHERE LastName = [Enter a Last Name:];
The next example prompts the user to provide a category ID and then uses that entry as
the criteria for the query:
PARAMETERS [Enter a Category ID:] Value;
SELECT CategoryID, ProductName, Count([Order Details].OrderID) AS Tally
FROM Products
INNER JOIN [Order Details] ON Products.ProductID = [Order Details].ProductID
GROUP BY CategoryID, ProductName
HAVING CategoryID = [Enter a Category ID:];
SQL - Query, Parameter Parameter Queries
Examples
To try the following examples in Microsoft Access, first create a new query in the
Northwind sample database. Close the Show Table dialog box without specifying a
table or query. Switch to SQL view, paste an individual example into the SQL window,
and run the query.
The following example prompts the user to provide an employee's last name and then
uses that entry as the criteria for the query:
PARAMETERS [Enter a Last Name:] Text;
SELECT *
FROM Employees
WHERE LastName = [Enter a Last Name:];
The next example prompts the user to provide a category ID and then uses that entry
as the criteria for the query:
PARAMETERS [Enter a Category ID:] Value;
SELECT CategoryID, ProductName, Count([Order Details].OrderID) AS Tally
FROM Products
INNER JOIN [Order Details] ON Products.ProductID = [Order Details].ProductID
GROUP BY CategoryID, ProductName
HAVING CategoryID = [Enter a Category ID:];
from..
Allen Browne's tips for Access users
Method 1: Parameter query
The simpest approach is to base the report on a parameter query. This approach
works for all kinds of queries, but has these disadvantages:
Inflexible: both dates must be entered.
Inferior interface: two separate dialog boxes pop up
No way to supply defaults.
No way to validate the dates.
To create the parameter query:
Create a query to use as the RecordSource of your report.
In query design view, in the Criteria row under your date field, enter:
Between [StartDate] And [EndDate]
Choose Parameters from the Query menu, and declare two parameters of type
Date/Time:
StartDate Date/Time
EndDate Date/Time
To display the limiting dates on the report, open your report in Design View,
and add two text boxes to the Report Header section. Set their ControlSource
property to =StartDate and =EndDate respectively.
(Note: Step 3 is optional, but strongly recommended. It prevents invalid dates
being entered, and helps Access understand the date regardless of your regional
setting date format.)
Method 2: Form for entering the dates
The alternative is to use a small unbound form where the user can enter the
limiting dates. This approach does not work with aggregate (GROUP BY) or crosstab
(TRANSFORM) queries, but has these advantages:
Flexible: user does not have to limit report to from and to dates.
Better interface: allows defaults and other mechanisms for choosing dates.
Validation: can verify the date entries.
Here are the steps. This example assumes a report named rptSales, limited by values
in the SaleDate field.
Create a new form that is not bound to any query or table. Save with the name
frmWhatDates.
Add two text boxes, and name them StartDate and EndDate. Set their Format property
to Short Date, so only date entries will be accepted.
Add two command buttons for Ok and Cancel. Set the Ok button's Default property to
Yes, and the Cancel button's Cancel property set to Yes.
Set the On Click property for both buttons to [Event Procedure]. Beside this is a
"..." button which opens the code window to the procedure.
Enter this line into Cancel button's Click procedure
(between the "Private Sub ..." and "End Sub" lines):
DoCmd.Close acForm, Me.Name
Paste this into the Ok button's Click procedure:
Dim strReport As String 'Name of report to open.
Dim strField As String 'Name of your date field.
Dim strWhere As String 'Where condition for OpenReport.
Const conDateFormat = "\#mm\/dd\/yyyy\#"
strReport = "rptSales"
strField = "SaleDate"
If IsNull(Me.txtStartDate) Then
If Not IsNull(Me.txtEndDate) Then 'End date, but no start.
strWhere = strField & " < " & Format(Me.txtEndDate, conDateFormat)
End If
Else
If IsNull(Me.txtEndDate) Then 'Start date, but no End.
strWhere = strField & " > " & Format(Me.txtStartDate, conDateFormat)
Else 'Both start and end dates.
strWhere = strField & " Between " & Format(Me.txtStartDate, conDateFormat) _
& " And " & Format(Me.txtEndDate, conDateFormat)
End If
End If
' Debug.Print strWhere 'For debugging purposes only.
DoCmd.OpenReport strReport, acViewPreview, , strWhere
Open the report in Design View, and add two text boxes to the report header for
displaying the date range. Set the ControlSource for these text boxes to:
=Forms.frmWhatDates.StartDate
=Forms.frmWhatDates.EndDate
SQL - SELECT STATEMENT
Instructs the Microsoft Jet database engine to return information from the database
as a set of records.
Syntax
SELECT [predicate] { * | table.* | [table.]field1 [AS alias1] [, [table.]field2
[AS alias2] [, ...]]}
FROM tableexpression [, ...] [IN externaldatabase]
[WHERE... ]
[GROUP BY... ]
[HAVING... ]
[ORDER BY... ]
[WITH OWNERACCESS OPTION]
The SELECT statement has these parts:
Part Description
predicate One of the following predicates: ALL, DISTINCT, DISTINCTROW,
or TOP. You use the predicate to restrict the number of records
returned. If none is specified, the default is ALL.
* Specifies that all fields from the specified table or tables are
selected.
table The name of the table containing the fields from which records
are selected.
field1, field2 The names of the fields containing the data you want to retrieve.
If you include more than one field, they are retrieved in the
order listed.
alias1, alias2 The names to use as column headers instead of the original column
names in table.
tableexpression The name of the table or tables containing the data you want to
retrieve.
externaldatabase The name of the database containing the tables in tableexpression
if they are not in the current database.
Remarks
To perform this operation, the Microsoft Jet database engine searches the specified table
or tables, extracts the chosen columns, selects rows that meet the criterion, and sorts or
groups the resulting rows into the order specified.
SELECT statements don't change data in the database.
SELECT is usually the first word in an SQL statement. Most SQL statements are either SELECT
or SELECT...INTO statements.
The minimum syntax for a SELECT statement is:
SELECT fields FROM table
You can use an asterisk (*) to select all fields in a table. The following example selects
all of the fields in the Employees table:
SELECT * FROM Employees;
If a field name is included in more than one table in the FROM clause, precede it with
the table name and the . (dot) operator. In the following example, the Department field
is in both the Employees table and the Supervisors table. The SQL statement selects
departments from the Employees table and supervisor names from the Supervisors table:
SELECT Employees.Department, Supervisors.SupvName
FROM Employees INNER JOIN Supervisors
WHERE Employees.Department = Supervisors.Department;
When a Recordset object is created, the Microsoft Jet database engine uses the table's
field name as the Field object name in the Recordset object. If you want a different
field name or a name isn't implied by the expression used to generate the field, use the
AS reserved word. The following example uses the title Birth to name the returned Field
object in the resulting Recordset object:
SELECT BirthDate
AS Birth FROM Employees;
Whenever you use aggregate functions or queries that return ambiguous or duplicate Field
object names, you must use the AS clause to provide an alternate name for the Field object.
The following example uses the title HeadCount to name the returned Field object in the
resulting Recordset object:
SELECT COUNT(EmployeeID)
AS HeadCount FROM Employees;
You can use the other clauses in a SELECT statement to further restrict and organize
your returned data. For more information, see the Help topic for the clause you're
using.
Examples (Access)
The following example selects the LastName and FirstName fields of all records in the
Employees table:
SELECT LastName, FirstName FROM Employees;
The next example selects all fields from the Employees table:
SELECT * FROM Employees;
The following example counts the number of records that have an entry in the PostalCode
field and names the returned field Tally:
SELECT Count(PostalCode) AS Tally FROM Customers;
The next example shows what product unit prices would be if each were increased by 10
percent. It doesn't change the existing unit prices in the database.
SELECT ProductName, UnitPrice AS Current, UnitPrice * 1.1 AS ProposedNewPrices
FROM Products;
The following example calculates the number of products in the database and the average
and maximum unit prices:
SELECT Count(*) AS [Total Products], Avg(UnitPrice) AS [Average Unit Price], Max(UnitPrice)
AS [Maximum Unit Price] FROM Products;
The next example displays the ProductName and UnitPrice for each record in the Products
table. The string "has a unit price of" separates the two fields in the result set.
SELECT ProductName, 'has a unit price of', UnitPrice FROM Products;
Example (DAO)
Some of the following examples assume the existence of a hypothetical Salary field in
an Employees table. Note that this field does not actually exist in the Northwind database
Employees table.
This example creates a dynaset-type Recordset based on an SQL statement that selects
the LastName and FirstName fields of all records in the Employees table. It calls the
EnumFields procedure, which prints the contents of a Recordset object to the Debug window.
Sub SelectX1()
Dim dbs As Database, rst As Recordset
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Select the last name and first name values of all records in the Employees table.
Set rst = dbs.OpenRecordset("SELECT LastName, " _
& "FirstName FROM Employees;")
' Populate the recordset.
rst.MoveLast
' Call EnumFields to print the contents of the Recordset.
EnumFields rst,12
dbs.Close
End Sub
This example counts the number of records that have an entry in the PostalCode field
and names the returned field Tally.
Sub SelectX2()
Dim dbs As Database, rst As Recordset
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Count the number of records with a PostalCode value and return the total in the
' Tally field.
Set rst = dbs.OpenRecordset("SELECT Count " _
& "(PostalCode) AS Tally FROM Customers;")
' Populate the Recordset.
rst.MoveLast
' Call EnumFields to print the contents of the Recordset. Specify field width = 12.
EnumFields rst, 12
dbs.Close
End Sub
This example shows the number of employees and the average and maximum salaries.
Sub SelectX3()
Dim dbs As Database, rst As Recordset
' Modify this line to include the path to Northwind
' on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Count the number of employees, calculate the average salary, and return the
' highest salary.
Set rst = dbs.OpenRecordset("SELECT Count (*) " _
& "AS TotalEmployees, Avg(Salary) " _
& "AS AverageSalary, Max(Salary) " _
& "AS MaximumSalary FROM Employees;")
' Populate the Recordset.
rst.MoveLast
' Call EnumFields to print the contents of the Recordset. Pass the Recordset
' object and desired field width.
EnumFields rst, 17
dbs.Close
End Sub
The Sub procedure EnumFields is passed a Recordset object from the calling procedure.
The procedure then formats and prints the fields of the Recordset to the Debug window.
The intFldLen variable is the desired printed field width. Some fields may be truncated.
Sub EnumFields(rst As Recordset, intFldLen As Integer)
Dim lngRecords As Long, lngFields As Long
Dim lngRecCount As Long, lngFldCount As Long
Dim strTitle As String, strTemp As String
' Set the lngRecords variable to the number of records in the Recordset.
lngRecords = rst.RecordCount
' Set the lngFields variable to the number of fields in the Recordset.
lngFields = rst.Fields.Count
Debug.Print "There are " & lngRecords _
& " records containing " & lngFields _
& " fields in the recordset."
Debug.Print
' Form a string to print the column heading.
strTitle = "Record "
For lngFldCount = 0 To lngFields - 1
strTitle = strTitle _
& Left(rst.Fields(lngFldCount).Name _
& Space(intFldLen), intFldLen)
Next lngFldCount
' Print the column heading.
Debug.Print strTitle
Debug.Print
' Loop through the Recordset; print the record number and field values.
rst.MoveFirst
For lngRecCount = 0 To lngRecords - 1
Debug.Print Right(Space(6) & _
Str(lngRecCount), 6) & " ";
For lngFldCount = 0 To lngFields - 1
' Check for Null values.
If IsNull(rst.Fields(lngFldCount)) Then
strTemp = ""
Else
' Set strTemp to the field contents.
Select Case _
rst.Fields(lngFldCount).Type
Case 11
strTemp = ""
Case dbText, dbMemo
strTemp = _
rst.Fields(lngFldCount)
Case Else
strTemp = _
str(rst.Fields(lngFldCount))
End Select
End If
Debug.Print Left(strTemp _
& Space(intFldLen), intFldLen);
Next lngFldCount
Debug.Print
rst.MoveNext
Next lngRecCount
End Sub
SQL - SELECT...INTO STATEMENT
Creates a make-table query.
Syntax
SELECT field1[, field2[, ...]] INTO newtable [IN externaldatabase]
FROM source
The SELECT...INTO statement has these parts:
Part Description
field1, field2 The name of the fields to be copied into the new table.
newtable The name of the table to be created. It must conform to
standard naming conventions. If newtable is the same as
the name of an existing table, a trappable error occurs.
externaldatabase The path to an external database. For a description of
the path, see the IN clause.
source The name of the existing table from which records are
selected. This can be single or multiple tables or a query.
Remarks
You can use make-table queries to archive records, make backup copies of your tables,
or make copies to export to another database or to use as a basis for reports that
display data for a particular time period. For example, you could produce a Monthly
Sales by Region report by running the same make-table query each month.
Notes
You may want to define a primary key for the new table. When you create the table,
the fields in the new table inherit the data type and field size of each field in the
query's underlying tables, but no other field or table properties are transferred.
To add data to an existing table, use the INSERT INTO statement instead to create an
append query.
To find out which records will be selected before you run the make-table query, first
examine the results of a SELECT statement that uses the same selection criteria.
Example (Access)
To try the following examples in Microsoft Access, first create a new query in the
Northwind sample database. Close the Show Table dialog box without specifying a table
or query. Switch to SQL view, paste an individual example into the SQL window, and
run the query.
The following example selects all records in the Employees table and copies them into
a new table named Employees Backup:
SELECT * INTO [Employees Backup] FROM Employees;
The next example creates a new table called Sales Representatives that contains only
employee records that have the title Sales Representative:
SELECT Employees.FirstName, LastName INTO [Sales Representatives]
FROM Employees
WHERE Title = 'Sales Representative';
The following example makes a copy of the Employees table and places the new table in
the assumed database Backup.mdb:
SELECT Employees.* INTO Employees IN Backup.mdb FROM Employees;
The next example assumes a Payroll table with two fields: EmployeeID and Salary. This
example creates a new table that contains employee and payroll data for all trainees.
The Employees and Payroll tables have a one-to-one relationship. The new table contains
all of the data from the Employees table plus the Salary field from the Payroll table.
SELECT Employees.*, Salary INTO Trainees
FROM Employees
INNER JOIN Payroll ON Employees.EmployeeID = Payroll.EmployeeID
WHERE Title = 'Trainee';
Example (DAO)
This example selects all records in the Employees table and copies them into a new table
named Emp Backup.
Sub SelectIntoX()
Dim dbs As Database
Dim qdf As QueryDef
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Select all records in the Employees table and copy them into a new table, Emp Backup.
dbs.Execute "SELECT Employees.* INTO " _
& "[Emp Backup] FROM Employees;"
' Delete the table because this is a demonstration.
dbs.Execute "DROP TABLE [Emp Backup];"
dbs.Close
End Sub
SQL - Subqueries
A subquery is a SELECT statement nested inside a SELECT, SELECT...INTO, INSERT...INTO,
DELETE, or UPDATE statement or inside another subquery.
Syntax
You can use three forms of syntax to create a subquery:
comparison [ANY | ALL | SOME] (sqlstatement)
expression [NOT] IN (sqlstatement)
[NOT] EXISTS (sqlstatement)
A subquery has these parts:
Part Description
comparison An expression and a comparison operator that compares the expression
with the results of the subquery.
expression An expression for which the result set of the subquery is searched.
sqlstatement A SELECT statement, following the same format and rules as any other
SELECT statement. It must be enclosed in parentheses.
Remarks
You can use a subquery instead of an expression in the field list of a SELECT statement
or in a WHERE or HAVING clause. In a subquery, you use a SELECT statement to provide a
set of one or more specific values to evaluate in the WHERE or HAVING clause expression.
Use the ANY or SOME predicate, which are synonymous, to retrieve records in the main query
that satisfy the comparison with any records retrieved in the subquery. The following
example returns all products whose unit price is greater than that of any product sold at
a discount of 25 percent or more:
SELECT * FROM Products
WHERE UnitPrice > ANY
(SELECT UnitPrice FROM OrderDetails
WHERE Discount >= .25);
Use the ALL predicate to retrieve only those records in the main query that satisfy the
comparison with all records retrieved in the subquery. If you changed ANY to ALL in the
previous example, the query would return only those products whose unit price is greater
than that of all products sold at a discount of 25 percent or more. This is much more
restrictive.
Use the IN predicate to retrieve only those records in the main query for which some
record in the subquery contains an equal value. The following example returns all
products with a discount of 25 percent or more:
SELECT * FROM Products
WHERE ProductID IN
(SELECT ProductID FROM OrderDetails
WHERE Discount >= .25);
Conversely, you can use NOT IN to retrieve only those records in the main query for which
no record in the subquery contains an equal value.
Use the EXISTS predicate (with the optional NOT reserved word) in true/false comparisons to
determine whether the subquery returns any records.
You can also use table name aliases in a subquery to refer to tables listed in a FROM
clause outside the subquery. The following example returns the names of employees whose
salaries are equal to or greater than the average salary of all employees having the same
job title. The Employees table is given the alias "T1":
SELECT LastName,
FirstName, Title, Salary
FROM Employees AS T1
WHERE Salary >=
(SELECT Avg(Salary)
FROM Employees
WHERE T1.Title = Employees.Title) Order by Title;
In the preceding example, the AS reserved word is optional.
Some subqueries are allowed in crosstab queries specifically, as predicates (those
in the WHERE clause). Subqueries as output (those in the SELECT list) are not allowed
in crosstab queries.
Example (Access)
The following example shows all non-discounted orders whose total is higher than
the average order value:
SELECT OrderID, (UnitPrice * Quantity) As OrderTotal FROM [Order Details]
WHERE Discount = 0 AND (UnitPrice * Quantity) > ALL(SELECT Avg(UnitPrice * Quantity)
FROM [Order Details]);
The next example lists the name and unit price of every product whose unit price is the
same as that of Aniseed Syrup:
SELECT ProductName, UnitPrice FROM Products
WHERE UnitPrice = (SELECT UnitPrice FROM [Products]
WHERE ProductName = 'Aniseed Syrup');
The following example lists the company and contact of every customer who placed an
order in the second quarter of 1995:
SELECT ContactName, CompanyName, ContactTitle, Phone FROM Customers
WHERE CustomerID IN (SELECT CustomerID FROM Orders WHERE OrderDate
BETWEEN #04/1/95# AND #06/30/95#);
The next example selects the name of every employee who has booked at least one order.
This could also be done with an INNER JOIN.
SELECT FirstName, LastName FROM Employees
WHERE EXISTS (SELECT OrderID FROM Orders
WHERE Orders.EmployeeID = Employees.EmployeeID);
Example (DAO)
This example lists the name and contact of every customer who placed an order in the
second quarter of 1995.
This example calls the EnumFields procedure, which you can find in the SELECT statement
example.
Sub SubQueryX()
Dim dbs As Database, rst As Recordset
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' List the name and contact of every customer who placed an order in the second
' quarter of 1995.
Set rst = dbs.OpenRecordset("SELECT ContactName," _
& " CompanyName, ContactTitle, Phone" _
& " FROM Customers" _
& " WHERE CustomerID" _
& " IN (SELECT CustomerID FROM Orders" _
& " WHERE OrderDate Between #04/1/95#" _
& " And #07/1/95#);")
' Populate the Recordset.
rst.MoveLast
' Call EnumFields to print the contents of the Recordset. Pass the Recordset object
' and desired field width.
EnumFields rst, 25
dbs.Close
End Sub
SQL - UPDATE STATEMENT
Creates an update query that changes values in fields in a specified table based on
specified criteria.
Syntax
UPDATE table
SET newvalue
WHERE criteria;
The UPDATE statement has these parts:
Part Description
table The name of the table containing the data you want to modify.
newvalue An expression that determines the value to be inserted into a particular
field in the updated records.
criteria An expression that determines which records will be updated. Only records
that satisfy the expression are updated.
Remarks
UPDATE is especially useful when you want to change many records or when the records that
you want to change are in multiple tables.
You can change several fields at the same time. The following example increases the Order
Amount values by 10 percent and the Freight values by 3 percent for shippers in the United
Kingdom:
UPDATE Orders
SET OrderAmount = OrderAmount * 1.1,
Freight = Freight * 1.03
WHERE ShipCountry = 'UK';
Important
UPDATE doesn't generate a result set. Also, after you update records using an update query,
you can't undo the operation. If you want to know which records were updated, first examine
the results of a select query that uses the same criteria, and then run the update query.
Maintain backup copies of your data at all times. If you update the wrong records,
you can
retrieve them from your backup copies.
Access Specifics
Since the UPDATE statement doesn't generate a result set, there is no query datasheet for
Microsoft Access to display when you use this statement.
If you want to confirm each change, you can use the Replace command on the Edit menu
of the form or datasheet rather than an update query.
Example (Access)
To try the following examples in Microsoft Access, first create a new query in the Northwind
sample database. Close the Show Table dialog box without specifying a table or query. Switch
to SQL view, paste an individual example into the SQL window, and run the query.
Warning These examples makes changes to the Northwind sample database. Before beginning,
you may wish to make a backup copy of the sample database.
The following example changes values in the ReportsTo field to 5 for all employee records
that currently have ReportsTo values of 2:
UPDATE Employees SET ReportsTo = 5 WHERE ReportsTo = 2;
The next example increases the UnitPrice for all non-discontinued products from supplier
#8 by 10 percent:
UPDATE Products SET UnitPrice = UnitPrice * 1.1
WHERE SupplierID = 8 AND Discontinued = No;
The following example reduces the UnitPrice for all non-discontinued products supplied by
Tokyo Traders by 5 percent. The Products and Suppliers tables have a many-to-one relationship.
UPDATE Suppliers INNER JOIN Products
ON Suppliers.SupplierID = Products.SupplierID SET UnitPrice = UnitPrice * .95
WHERE CompanyName = 'Tokyo Traders' AND Discontinued = No;
Example (DAO)
This example changes values in the ReportsTo field to 5 for all employee records that
currently have ReportsTo values of 2.
Sub UpdateX()
Dim dbs As Database
Dim qdf As QueryDef
' Modify this line to include the path to Northwind on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Change values in the ReportsTo field to 5 for all employee records that currently
' have ReportsTo values of 2.
dbs.Execute "UPDATE Employees " _
& "SET ReportsTo = 5 " _
& "WHERE ReportsTo = 2;"
dbs.Close
End Sub
SQL - WHERE Clause
Specifies which records from the tables listed in the FROM clause are affected by a
SELECT, UPDATE, or DELETE statement.
Syntax
SELECT fieldlist
FROM tableexpression
WHERE criteria
A SELECT statement containing a WHERE clause has these parts:
Part Description
fieldlist ` The name of the field or fields to be retrieved along with
any field-name aliases, selection predicates (ALL, DISTINCT,
DISTINCTROW, or TOP), or other SELECT statement options.
tableexpression The name of the table or tables from which data is retrieved.
criteria An expression that records must satisfy to be included in the
query results.
Remarks
The Microsoft Jet database engine selects the records that meet the conditions listed
in the WHERE clause. If you don't specify a WHERE clause, your query returns all rows
from the table. If you specify more than one table in your query and you haven't
included a WHERE clause or a JOIN clause, your query generates a Cartesian product
(producing all possible ordered combinations of rows from the table 1 with all rows
from table 2) of the tables.
WHERE is optional, but when included, follows FROM. For example, you can select all
employees in the sales department (WHERE Dept = 'Sales') or all customers between the
ages of 18 and 30 (WHERE Age Between 18 And 30).
If you don't use a JOIN clause to perform SQL join operations on multiple tables, the
resulting Recordset object won't be updatable.
WHERE is similar to HAVING. WHERE determines which records are selected. Similarly, once
records are grouped with GROUP BY, HAVING determines which records are displayed.
Use the WHERE clause to eliminate records you don't want grouped by a GROUP BY clause.
Use various expressions to determine which records the SQL statement returns. For
example, the following SQL statement selects all employees whose salaries are more
than $21,000:
SELECT LastName, Salary
FROM Employees
WHERE Salary > 21000;
A WHERE clause can contain up to 40 expressions linked by logical operators, such as
And and Or.
When you enter a field name that contains a space or punctuation, surround the name
with brackets ([ ]). For example, a customer information table might include information
about specific customers :
SELECT [Customer's Favorite Restarant]
When you specify the criteria argument, date literals must be in U.S. format, even if
you're not using the U.S. version of the Microsoft Jet database engine. For example,
May 10, 1996, is written 10/5/96 in the United Kingdom and 5/10/96 in the United States.
Be sure to enclose your date literals with the number sign (#) as shown in the following
examples.
To find records dated May 10, 1996 in a United Kingdom database, you must use the
following SQL statement:
SELECT *
FROM Orders
WHERE ShippedDate = #5/10/96#;
You can also use the DateValue function which is aware of the international settings
established by Microsoft Windows. For example, use this code for the United States:
SELECT *
FROM Orders
WHERE ShippedDate = DateValue('5/10/96');
And use this code for the United Kingdom:
SELECT *
FROM Orders
WHERE ShippedDate = DateValue('10/5/96');
Note If the column referenced in the criteria string is of type GUID, the criteria
expression uses a slightly different syntax:
WHERE ReplicaID = {GUID {12345678-90AB-CDEF-1234-567890ABCDEF}}
Be sure to include the nested braces and hyphens as shown.
Examples (Access)
To try the following examples in Microsoft Access, first create a new query in the
Northwind sample database. Close the Show Table dialog box without specifying a table
or query. Switch to SQL view, paste an individual example into the SQL window, and run
the query.
The following example selects the LastName and FirstName fields of each record in which
the last name is King:
SELECT LastName, FirstName FROM Employees
WHERE LastName = 'King';
The next example selects the LastName and FirstName fields for employees whose last
names begin with the letter S:
SELECT LastName, FirstName FROM Employees
WHERE LastName Like 'S*';
The following example selects products whose unit prices are between $20 and $50,
inclusive:
SELECT ProductName, UnitPrice FROM Products
WHERE (UnitPrice >=20.00 And UnitPrice <= 50.00);
The next example selects all products whose names fall in alphabetic order between
"Cha" and "Out", inclusive. It doesn't retrieve "Outback Lager" because "Outback Lager"
follows "Out" and therefore is outside the specified range.
SELECT ProductName, UnitPrice FROM Products
WHERE ProductName Between 'Cha' And 'Out';
The following example selects orders placed during the first half of 1995:
SELECT OrderID, OrderDate FROM Orders
WHERE OrderDate Between #1-1-95# And #6-30-95#;
The next example selects orders shipped to Idaho, Oregon, or Washington:
SELECT OrderID, ShipRegion FROM Orders
WHERE ShipRegion In ('ID', 'OR', 'WA');
Examples (DAO)
The following example assumes the existence of a hypothetical Salary field in an
Employees table. Note that this field does not actually exist in the Northwind
database Employees table.
This example selects the LastName and FirstName fields of each record in which the
last name is King.
This example calls the EnumFields procedure, which you can find in the SELECT
statement example.
Sub WhereX()
Dim dbs As Database, rst As Recordset
' Modify this line to include the path to Northwind
' on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Select records from the Employees table where the
' last name is King.
Set rst = dbs.OpenRecordset("SELECT LastName, " _
& "FirstName FROM Employees " _
& "WHERE LastName = 'King';")
' Populate the Recordset.
rst.MoveLast
' Call EnumFields to print the contents of the
' Recordset.
EnumFields rst, 12
dbs.Close
End Sub
STATEMENT - Call
Transfers control to a Sub procedure, Function procedure, or dynamic-link library (DLL)
procedure.
Syntax
[Call] name [argumentlist]
The Call statement syntax has these parts:
Part Description
Call Optional; keyword. If specified, you must enclose argumentlist in
parentheses. For example:
Call MyProc(0)
name Required. Name of the procedure to call.
argumentlist Optional. Comma-delimited list of variables, arrays, or expressions to
pass to the procedure. Components of argumentlist may include the keywords
ByVal or ByRef to describe how the arguments are treated by the called
procedure. However, ByVal and ByRef can be used with Call only when
calling a DLL procedure.
Remarks
You are not required to use the Call keyword when calling a procedure. However, if you
use the Call keyword to call a procedure that requires arguments, argumentlist must be
enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses
around argumentlist. If you use either Call syntax to call any intrinsic or user-defined
function, the function's return value is discarded.
To pass a whole array to a procedure, use the array name followed by empty parentheses.
STATEMENT - ForEach...Next
Repeats a group of statements for each element in an array or collection.
Syntax
For Each element In group
[statements]
[Exit For]
[statements]
Next [element]
The For...Each...Next statement syntax has these parts:
Part Description
element Required. Variable used to iterate through the elements of the collection
or array. For collections, element can only be a Variant variable, a generic
object variable, or any specific object variable. For arrays, element can
only be a Variant variable.
group Required. Name of an object collection or array (except an array of
user-defined types).
statements Optional. One or more statements that are executed on each item in group.
Remarks
The For...Each block is entered if there is at least one element in group. Once the loop
has been entered, all the statements in the loop are executed for the first element in group.
If there are more elements in group, the statements in the loop continue to execute for each
element. When there are no more elements in group, the loop is exited and execution continues
with the statement following the Next statement.
Any number of Exit For statements may be placed anywhere in the loop as an alternative way
to exit. Exit For is often used after evaluating some condition, for example If…Then, and
transfers control to the statement immediately following Next.
You can nest For...Each...Next loops by placing one For...Each...Next loop within another.
However, each loop element must be unique.
Note
If you omit element in a Next statement, execution continues as if element is included.
If a Next statement is encountered before its corresponding For statement, an error occurs.
You can't use the For...Each...Next statement with an array of user-defined types because
a Variant can't contain a user-defined type.
Example
This example uses the For Each...Next statement to search the Text property of all
elements in a collection for the existence of the string "Hello". In the example,
MyObject is a text-related object and is an element of the collection MyCollection.
Both are generic names used for illustration purposes only.
Dim Found, MyObject, MyCollection
Found = False ' Initialize variable.
For Each MyObject In MyCollection ' Iterate through each element.
If MyObject.Text = "Hello" Then ' If Text equals "Hello".
Found = True ' Set Found to True.
Exit For ' Exit loop.
End If
Next
Example (Excel)
This example loops on cells A1:D10 on Sheet1. If one of the cells has a value less than
0.001, the code replaces the value with 0 (zero).
For Each c in Worksheets("Sheet1").Range("A1:D10")
If c.Value < .001 Then
c.Value = 0
End If
Next c
This example loops on the range named "TestRange" and then displays the number of empty
cells in the range.
numBlanks = 0
For Each c In Range("TestRange")
If c.Value = "" Then
numBlanks = numBlanks + 1
End If
Next c
MsgBox "There are " & numBlanks & " empty cells in this range."
This example closes and saves changes to all workbooks except the one that's running
the example.
For Each w In Workbooks
If w.Name <> ThisWorkbook.Name Then
w.Close savechanges:=True
End If
Next w
This example deletes every worksheet in the active workbook without displaying the
confirmation dialog box. There must be at least one other visible sheet in the workbook.
Application.DisplayAlerts = False
For Each w In Worksheets
w.Delete
Next w
Application.DisplayAlerts = True
This example creates a new worksheet and then inserts into it a list of all the names
in the active workbook, including their formulas in A1-style notation in the language
of the user.
Set newSheet = ActiveWorkbook.Worksheets.Add
i = 1
For Each nm In ActiveWorkbook.Names
newSheet.Cells(i, 1).Value = nm.NameLocal
newSheet.Cells(i, 2).Value = "'" & nm.RefersToLocal
i = i + 1
Next nm
STATEMENT - SendKeys
also see.. MACROS - AutoKeys
Sends one or more keystrokes to the active window as if typed at the keyboard.
Syntax
SendKeys string[, wait]
The SendKeys statement syntax has these named arguments:
Part Description
string Required. String expression specifying the keystrokes to send.
Wait Optional. Boolean value specifying the wait mode. If False (default),
control is returned to the procedure immediately after the keys are sent.
If True, keystrokes must be processed before control is returned to the
procedure.
Remarks
Each key is represented by one or more characters. To specify a single keyboard character,
use the character itself. For example, to represent the letter A, use "A" for string. To
represent more than one character, append each additional character to the one preceding
it. To represent the letters A, B, and C, use "ABC" for string.
To specify any of the following special (SendKeys) characters, enclose them within
braces {}:
Character Use
plus sign {+}
caret {^}
percent sign {%}
tilde {~}
parentheses {(} and {)}
Brackets {[} and {]}
Note
Brackets have no special meaning to SendKeys, but must be enclosed in braces,
since in other applications, they can have a special meaning that may be significant when
dynamic data exchange (DDE) occurs.
In addition, to specify characters that aren't displayed when you press a key, such as
ENTER or TAB, or keys that represent actions rather than characters, use the following
bracketed codes:
Key Code
BACKSPACE {BACKSPACE}, {BS}, or {BKSP}
BREAK {BREAK}
CAPS LOCK {CAPSLOCK}
DEL or DELETE {DELETE} or {DEL}
DOWN ARROW {DOWN}
END {END}
ENTER {ENTER}or ~
ESC {ESC}
HELP {HELP}
HOME {HOME}
INS or INSERT {INSERT} or {INS}
LEFT ARROW {LEFT}
NUM LOCK {NUMLOCK}
PAGE DOWN {PGDN}
PAGE UP {PGUP}
PRINT SCREEN {PRTSC}
RIGHT ARROW {RIGHT}
SCROLL LOCK {SCROLLLOCK}
TAB {TAB}
UP ARROW {UP}
F1 {F1}
F2 {F2}
F3 {F3}
F4 {F4}
F5 {F5}
F6 {F6}
F7 {F7}
F8 {F8}
F9 {F9}
F10 {F10}
F11 {F11}
F12 {F12}
F13 {F13}
F14 {F14}
F15 {F15}
F16 {F16}
To specify keys combined with any combination of the SHIFT, CTRL, and ALT keys, precede the
key code with one or more of the following codes:
Key Code
SHIFT +
CTRL ^
ALT %
To specify that any combination of SHIFT, CTRL, and ALT should be held down while
several other keys are pressed, enclose the code for those keys in parentheses.
For example:
CTRL-C ^C
CTRL-P ^P
ALT-F %F
SHIFT-E-C (3 keys held) are pressed +(EC)
SHIFT-E, followed by C without SHIFT +EC
To specify repeating keys, use the form {key number-of-strikes} with a
space between key and number-of-strikes.
For example:
press the LEFT ARROW key 42 times {LEFT 42}
press H 10 times {h 10}
Note
You can't use SendKeys to send keystrokes to an application that is not designed to run in
Microsoft Windows. Sendkeys also can't send the PRINT SCREEN key {PRTSC} to any application.
Example
This example uses the Shell function to run the Calculator application included with
Microsoft Windows.It uses the SendKeys statement to send keystrokes to add some numbers,
and then quit the Calculator. The SendKeys statement is not available on the Macintosh.
(To see the example, paste it into a procedure, then run the procedure. Because AppActivate
changes the focus to the Calculator application, you can't single step through the code.)
Dim ReturnValue, I
ReturnValue = Shell("CALC.EXE", 1) ' Run Calculator
AppActivate ReturnValue ' Activate the Calculator
For I = 1 To 100 ' Set up counting loop
SendKeys I & "{+}", True ' Send keystrokes to Calculator
Next I ' to add each value of I
SendKeys "=", True ' Get grand total
SendKeys "%{F4}", True ' Send ALT+F4 to close Calculator
STATEMENT - SET
Assigns an object reference to a variable or property.
Syntax
Set objectvar = {[New] objectexpression | Nothing}
The Set statement syntax has these parts:
Part Description
objectvar Required. Name of the variable or property; follows standard
variable naming conventions.
New Optional. New is usually used during declaration to enable implicit
object creation. When New is used with Set, it creates a new instance
of the class. If objectvar contained a reference to an object, that
reference is released when the new one is assigned. The New keyword
can't be used to create new instances of any intrinsic data type and
can't be used to create dependent objects.
objectexpression Required. Expression consisting of the name of an object, another
declared variable of the same object type, or a function or method
that returns an object of the same object type.
Nothing Optional. Discontinues association of objectvar with any specific
object. Assigning Nothing to objectvar releases all the system and
memory resources associated with the previously referenced object
when no other variable refers to it.
Remarks
To be valid, objectvar must be an object type consistent with the object being assigned to it.
The Dim, Private, Public, ReDim, and Static statements only declare a variable that refers
to an object. No actual object is referred to until you use the Set statement to assign a
specific object.
The following example illustrates how Dim is used to declare an array with the type Form1.
No instance of Form1 actually exists. Set then assigns references to new instances of Form1
to the myChildForms variable. Such code might be used to create child forms in an MDI
application.
Dim myChildForms(1 to 4) As Form1
Set myChildForms(1) = New Form1
Set myChildForms(2) = New Form1
Set myChildForms(3) = New Form1
Set myChildForms(4) = New Form1
Generally, when you use Set to assign an object reference to a variable, no copy of the
object is created for that variable. Instead, a reference to the object is created. More
than one object variable can refer to the same object. Because such variables are references
to the object rather than copies of the object, any change in the object is reflected in
all variables that refer to it.
However, when you use the New keyword in the Set statement, you are actually
creating an instance of the object.
Example (Excel)
This example adds a new worksheet to the active workbook and then sets the name of
the worksheet.
Set newSheet = Worksheets.Add
newSheet.Name = "1995 Budget"
This example creates a new worksheet and then inserts into it a list of all the names
in the active workbook, including their formulas in A1-style notation in the language
Set newSheet = ActiveWorkbook.Worksheets.Add
i = 1
For Each nm In ActiveWorkbook.Names
newSheet.Cells(i, 1).Value = nm.NameLocal
newSheet.Cells(i, 2).Value = "'" & nm.RefersToLocal
i = i + 1
Next
QUERY - Subquery in a Calculated Field
Example
You enter the expression in the Field cell in the query design grid. The fields you
reference in the expression are from the tables or queries in the current query.
Expression
Cat: (SELECT [CategoryName] FROM [Categories]
WHERE [Products].[CategoryID]=[Categories].[CategoryID])
Description
Displays the CategoryName if the CategoryID from the Categories table is the same as
the CategoryID from the Products table.
SQL - UNION Operation
Creates a union query, which combines the results of two or more independent queries
or tables.
Syntax
[TABLE] query1 UNION [ALL] [TABLE] query2 [UNION [ALL] [TABLE] queryn [ ... ]]
The UNION operation has these parts:
Part Description
query1-n A SELECT statement, the name of a stored query, or the name of a
stored table preceded by the TABLE keyword.
Remarks
You can merge the results of two or more queries, tables, and SELECT statements, in
any combination, in a single UNION operation. The following example merges an existing
table named New Accounts and a SELECT statement:
TABLE [New Accounts] UNION ALL
SELECT *
FROM Customers
WHERE OrderAmount > 1000;
By default, no duplicate records are returned when you use a UNION operation; however,
you can include the ALL predicate to ensure that all records are returned. This also
makes the query run faster.
All queries in a UNION operation must request the same number of fields; however, the
fields don't have to be of the same size or data type.
Use aliases only in the first SELECT statement because they are ignored in any others.
In the ORDER BY clause, refer to fields by what they are called in the first SELECT
statement.
Notes
You can use a GROUP BY or HAVING clause in each query argument to group the
returned data.
You can use an ORDER BY clause at the end of the last query argument to display the
returned data in a specified order.
Examples (Access)
To try the following examples in Microsoft Access, first create a new query in the
Northwind sample database. Close the Show Table dialog box without specifying a table
or query. Switch to SQL view, paste an individual example into the SQL window, and
run the query.
The following example retrieves the names and cities of all suppliers and customers in
Brazil:
SELECT CompanyName, City FROM Suppliers
WHERE Country = 'Brazil'
UNION SELECT CompanyName, City FROM Customers
WHERE Country = 'Brazil';
The next example retrieves the names and cities of all suppliers and customers located
in Brazil:
SELECT CompanyName, City, 'Supplier' AS Source
FROM Suppliers
WHERE Country = 'Brazil'
UNION SELECT CompanyName, City, 'Customer'
FROM Customers
WHERE Country = 'Brazil'
ORDER BY City, Source;
The following example retrieves the names and IDs of all suppliers and customers. This
union assumes that there are the same number of columns in each table.
TABLE Customers UNION TABLE Suppliers;
Example (DAO)
This example retrieves the names and cities of all suppliers and customers in Brazil.
This example calls the EnumFields procedure, which you can find in the SELECT statement
example.
Sub UnionX()
Dim dbs As Database, rst As Recordset
' Modify this line to include the path to Northwind
' on your computer.
Set dbs = OpenDatabase("Northwind.mdb")
' Retrieve the names and cities of all suppliers
' and customers in Brazil.
Set rst = dbs.OpenRecordset("SELECT CompanyName," _
& " City FROM Suppliers" _
& " WHERE Country = 'Brazil' UNION" _
& " SELECT CompanyName, City FROM Customers" _
& " WHERE Country = 'Brazil';")
' Populate the Recordset.
rst.MoveLast
' Call EnumFields to print the contents of the
' Recordset. Pass the Recordset object and desired
' field width.
EnumFields rst, 12
dbs.Close
End Sub
===============================
TEMPORARY ENTRY TO BE EDITED
===============================
Temp... Edit and Move to Section starting with..
"Problem: My Report contains a field that is formatted."
Ian Sargent
Mar 9 2002 21:27 Folks,
I seem to have a weird problem with converting a date for use in an SQL statement:
I am using MS WIndows XP and Office 2000 Developer
1. I am located in the UK and so all my forms etc use dd/mm/yy format!
2. In SQL I know you MUST use mm/dd/yy format!
Given the above lets try a Start_Date of 12th August 2001 or dd/mm/yy = 12/08/01 If I
then use this code (for use later in SQL):
StartDate = Month(Start_Date) & "/" & Day(Start_Date) & "/" & Year(Start_Date)
StartDate is then 08/12/01 (mm/dd/yy) - so far so good!
If however I use a Start_Date of 13th August 2001 or 13/08/01
StartDate ends up as 13/08/01 ????
It would appear that if I use a DAY value GREATER than 12 things get screwed up - and
my SQL ends up ......
Has anyone ANY idea what I am doing wrong - as I am sure it must be me?!?!
Regards Ian
--
DON'T just reply to message, use the email below! The 'reply to' address may be an
'anti spam' address
_____________________________________
Ian Sargent Education & Training Consulting Services Ltd Tel/Fax: 01344 644579
Mobile: 07970 847197 email: ians@etcs.co.uk www: http://www.etcs.co.uk
_____________________________________
John Vinson
Mar 9 2002 21:27 On Sat, 9 Mar 2002 18:20:31 -0000, "Ian Sargent" wrote:
> StartDate = Month(Start_Date) & "/" & Day(Start_Date) & "/" & Year(Start_Date)
Access is interpreting the date string in accordance with your system settings. DIM
StartDate as a String instead of as a Date, and use
StartDate = Format(Start_Date, "mm/dd/yyyy")
instead.
John W. Vinson[MVP]
Come for live chats every Tuesday and Thursday
http://go.compuserve.com/msdevapps?loc=us&access=public
Douglas J. Steel
Mar 9 2002 21:27 Don't assign the value to StartDate: use a format statement in your SQL.
Presumably you've got something like:
strSQL = strSQL & "WHERE [MyDateField] >= #" & StartDate & "#"
Change that to:
strSQL = strSQL & "WHERE [MyDateField] >= " & Format$(StartDate, "\#mm\/dd\/yyyy\#")
Assuming StartDate has been defined as a Date, what you're storing in it isn't
necessarily what you think it is!
Dates are stored as 8 byte floating point numbers, where the integer part represents
the number of days relative to 29 Dec, 1899, and the decimal part represents the time
as a fraction of a day (eg.: 6:00 AM is .25, Noon is .5,
6:00 PM is .75, and so on). They don't actually care about the format at all.
When you pass something to a date field that isn't a date, Access will do its best to
interpret it for you. If you pass it a string ##/##/##, it'll try and convert it to a
date. Being an American company, in the absence of any other instructions, it'll
assume a mm/dd/yyyy format. If it can't use that format, it'll try a few other
possibilities before it gives up. If you use the DateValue function, it will respect
your local settings.
Try running the following code:
Sub TestDateFormat()
Dim dtmDate As Date
Debug.Print "String 12/08/01" dtmDate = "12/08/01" Debug.Print dtmDate & " (" &
Format$(dtmDate, "dd-mmm-yyyy") & ")"
Debug.Print
dtmDate = DateSerial(2001, 8, 12)
Debug.Print "using Month, Day, Year functions" dtmDate = Month(dtmDate) & "/" &
Day(dtmDate) & "/" & Year(dtmDate) Debug.Print dtmDate & " (" & Format$(dtmDate,
"dd-mmm-yyyy") & ")"
Debug.Print
Debug.Print "String 13/08/01" dtmDate = "13/08/01" Debug.Print dtmDate & " (" &
Format$(dtmDate, "dd-mmm-yyyy") & ")"
Debug.Print
dtmDate = DateSerial(2001, 8, 13)
Debug.Print "using Month, Day, Year functions" dtmDate = Month(dtmDate) & "/" &
Day(dtmDate) & "/" & Year(dtmDate) Debug.Print dtmDate & " (" & Format$(dtmDate,
"dd-mmm-yyyy") & ")"
End Sub
With your short date format set to dd/mm/yy, you should get:
TestDateFormat String 12/08/01
6/1/01 (12-Aug-2001)
using Month, Day, Year functions
6/2/01 (08-Dec-2001)
String 13/08/01
6/3/01 (13-Aug-2001)
using Month, Day, Year functions
6/4/01 (13-Aug-2001)
You might find it useful to read Allen Browne's "International Dates in Access" at:
http://users.bigpond.net.au/abrowne1/ser-36.html
--
Doug Steele, Microsoft Access MVP http://I.Am/DougSteele
"Ian Sargent" wrote in message
news:_nsi8.6098$xO2.409094@news11-gui.server.ntli.net...
> Folks,
>
> I seem to have a weird problem with converting a date for use in an SQL statement:
>
> I am using MS WIndows XP and Office 2000 Developer
>
> 1. I am located in the UK and so all my forms etc use dd/mm/yy format!
> 2. In SQL I know you MUST use mm/dd/yy format!
>
> Given the above lets try a Start_Date of 12th August 2001 or dd/mm/yy = 12/08/01 If
> I then use this code (for use later in SQL):
>
> StartDate = Month(Start_Date) & "/" & Day(Start_Date) & "/" & Year(Start_Date)
>
> StartDate is then 08/12/01 (mm/dd/yy) - so far so good!
>
> If however I use a Start_Date of 13th August 2001 or 13/08/01
>
> StartDate ends up as 13/08/01 ????
>
> It would appear that if I use a DAY value GREATER than 12 things get screwed up -
> and my SQL ends up ......
>
> Has anyone ANY idea what I am doing wrong - as I am sure it must be me?!?!
>
> Regards Ian
John Nurick
Mar 9 2002 21:27 Hi Ian,
I can't make this happen in Access 2002 and am pretty sure it doesn't happen in
Access 97, so suspect there's something funny going on.
First thing to do is to check the Date settings in the Regional Settings control
panel applet (or whatever WinXP has). Make sure that it's set to "dd/MM/yy" for
Short Date.
Second, try using explicit type conversions and date functions. This is how I
usually do it:
Function SQLDate(strDate As String) As String SQLDate = "#" & Format(CDate(strDate),
"mm/dd/yy") & "#" End Function
On Sat, 9 Mar 2002 18:20:31 -0000, "Ian Sargent" wrote:
>I seem to have a weird problem with converting a date for use in an SQL statement:
>
>I am using MS WIndows XP and Office 2000 Developer
>
>1. I am located in the UK and so all my forms etc use dd/mm/yy format!
>2. In SQL I know you MUST use mm/dd/yy format!
>
>Given the above lets try a Start_Date of 12th August 2001 or dd/mm/yy = 12/08/01 If
>I then use this code (for use later in SQL):
>
> StartDate = Month(Start_Date) & "/" & Day(Start_Date) & "/" & Year(Start_Date)
>
>StartDate is then 08/12/01 (mm/dd/yy) - so far so good!
>
>If however I use a Start_Date of 13th August 2001 or 13/08/01
>
>StartDate ends up as 13/08/01 ????
>
>It would appear that if I use a DAY value GREATER than 12 things get screwed up -
>and my SQL ends up ......
John Nurick [Access MVP]
Please do not respond by email, but to the newgroup.
Chris Mills
Mar 10 2002 6:22 In addition to the other replies...
Access will *automatically swap* mm/dd & dd/mm in SQL if it detects that *one is
valid and the other not*.
That's your answer, the rest of this is expansion.
This auto-correction sounds great, except of course it can only correct some dates,
so if you do any date checking on or after 12th of the month, your code will work
just fine whatever you do! Thinks...must test before the 12th...
The issue applies to all Access SQL including that generated by code. The SQL is not
dependent on regional settings(must be mm/dd/yy), unfortunately the code to generate
the SQL is dependent, though if it ends up as #31/01/02# auto-correction kicks-in and
you will never know there is an error. Also, if StartDate is defined as a variant or
can otherwise be interpreted as a date rather than a string, basically you have lost
control of exactly how it is formatted (i.e. make sure it's a string)
As a matter of interest, stick some ambiguous #mm/dd/yy# or vice-versa in the Query
Wizard, and if you have dd/mm/yy regional settings just watch it change between SQL
view and Query view.
Though I've sussed it, I've taken to using a format of #dd mmm yyyy# for SQL which
completely avoids the US problem. So easy to make a mistake whilst testing after the
12th or on 1/1, 2/2 etc. The only objection I heard was that it is then
language-dependent.
Chris (former colony, still regretting it for reasons like this )
"Ian Sargent" wrote in message
news:_nsi8.6098$xO2.409094@news11-gui.server.ntli.net...
> Folks,
>
> I seem to have a weird problem with converting a date for use in an SQL statement:
>
> I am using MS WIndows XP and Office 2000 Developer
>
> 1. I am located in the UK and so all my forms etc use dd/mm/yy format!
> 2. In SQL I know you MUST use mm/dd/yy format!
>
> Given the above lets try a Start_Date of 12th August 2001 or dd/mm/yy = 12/08/01 If
> I then use this code (for use later in SQL):
>
> StartDate = Month(Start_Date) & "/" & Day(Start_Date) & "/" & Year(Start_Date)
>
> StartDate is then 08/12/01 (mm/dd/yy) - so far so good!
>
> If however I use a Start_Date of 13th August 2001 or 13/08/01
>
> StartDate ends up as 13/08/01 ????
>
> It would appear that if I use a DAY value GREATER than 12 things get screwed up -
> and my SQL ends up ......
>
> Has anyone ANY idea what I am doing wrong - as I am sure it must be me?!?!
>
> Regards Ian
>
> --
> DON'T just reply to message, use the email below! The 'reply to' address may be an
> 'anti spam' address
> _____________________________________
> Ian Sargent Education & Training Consulting Services Ltd Tel/Fax: 01344 644579
> Mobile: 07970 847197 email: ians@etcs.co.uk www: http://www.etcs.co.uk
> _____________________________________