1. Trang chủ
  2. » Công Nghệ Thông Tin

Access 2007 VBA Programmer’s Reference phần 9 doc

115 308 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 115
Dung lượng 448,46 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Properties of the Record Object The following table describes the properties associated with a Recordobject.. Size Long Specifies the current size of the stream of data.State ObjectState

Trang 1

Property DataType Description

the command text or stream

the associated Connectionobject

NamedParameters Boolean Indicates whether parameter names are passed

to the provider

Prepared Boolean True if the provider should save a compiled

ver-sion of a Commandbefore execution

open, closed, or in the process of connecting,executing, or retrieving information

Methods of the Command Object

Methods of the Commandobjects are used to work with a particular command that will be executed onthe Connectionobject To execute a Commandobject, just call it by its Nameproperty on the associatedConnectionobject

Execute Executes the particular command stored in the CommandTextproperty

Collections of the Command Object

Trang 2

Parameter s Collection

The Commandobject has a Parameterscollection associated with it that contains all of the Parameterobjects of the Commandobject The actual Parameterscollection does not contain any properties or col-lections, only methods

Methods of the Parameters Collection

There are exactly three methods for the Parameterscollection They are described in the following table

Append Parameterobject Used to add a Parameterobject to the collection.Refresh None Updates all of the Parameterobjects in the collec-

tion with the latest information from the provider

The Indexvalue is either the name or ordinal tion of the Parameterin the collection

posi-Properties of the Parameter Object

Each Parameterobject in the Parameterscollection contains the actual data for the parameter The lowing table describes the various properties of the Parameterobjects

one or more ParameterAttributesEnumues The default value is adParamSigned.Direction ParameterDirectionEnum Indicates if the Parameterrepresents an input

val-parameter, an output val-parameter, an input and

an output parameter, or if the parameter is thereturn value from a stored procedure

NumericScale Byte Sets or returns a byte value that indicates the

number of decimal places to which numeric ues are resolved

Parameterobject This sets or returns a Bytefield to represent the maximum number of dig-its used to represent values

Table continues on the next page

879

Appendix E: ADO Object Model Reference

Trang 3

Property DataType Description

Size Long Indicates the maximum size in either bytes or

characters of the Parameterobject

Type DataTypeEnum Indicates the data type of the Parameter

value of the Parameter

Method of the Parameter Object

The only method available for the Parameterobject is AppendChunk It simply appends data to theParameterobject Use the CreateParametermethod of the Commandobject to create a Parameterwith a specific name and properties Then use the Appendmethod to add the newly created Parameter

to the Parameterscollection

AppendChunk Adds a Parameterto the Parameterscollection

Collections of the Parameter Object

There is exactly one collection for the Parameterobject —Properties

or properties may not be available

Properties of the Recordset Object

The Recordsetobject has a variety of properties and methods you’ll use in your programming The lowing table describes the properties

Trang 4

fol-Property DataType Description

AbsolutePage Long Identifies the page the current record of the

Recordsetis on

AbsolutePosition Long Identifies the position of the current record in

the Recordset.ActiveCommand Variant Pointer to the Commandobject that created the

Recordset.ActiveConnection Stringor Connection Specifies the Connectionobject used to retrieve

the Recordset

file, the position before the first record

Bookmark Variant Allows you to return to a specific record in the

Recordset

server

CursorLocation Long Lists whether the cursor service that maintain

the results of the query is client-side or server-side

CursorType CursorTypeEnum Specifies the type of cursor used to access

the query results (dynamic, keyset, status, ward-only)

you’re referring to

data source

EditMode EditModeEnum Specifies the editing status for the current

record

position after the last record in yourRecordset

partic-ular values

Recordset.LockType LockTypeEnum Controls how the contents of the Recordsetare

locked and updated

MarshalOptions MarshalOptionEnum Specifies which records are transferred back to

Trang 5

Property DataType Description

of records returned by the query

the query string used for the Recordset.StayInSync Boolean True if the child record needs to be kept

updated

Status RecordStatusEnum Stores the update status of the current record

There are two common properties used when working with a Recordsetobject The first, and probablymost important, is the Fieldscollection This collection stores all of the fields that contain the results of

a given query The second is the Propertiescollection, a collection of dynamic properties associatedwith Recordset

Methods of the Recordset Object

You’ll use a number of methods when manipulating your Recordsetobject as well Those methods arelisted in the following table

AddNew Adds a new record to the Recordset

Cancel Cancels the execution of an asynchronous query

CancelBatch Cancels pending changes in a Recordsetthat uses batch optimistic

updates

CancelUpdate Cancels pending changes currently being edited

Clone Creates a new reference to the Recordsetthat allows navigation

inde-pendently from the original Recordset.Close Closes the Recordsetobject and releases its contents

CompareBookmarks Compares two bookmarks in the same Recordset

Trang 6

Method Description

Delete Deletes the current record in the Recordset.Find Searches the Recordsetfor a record based on the string criteria

GetRows Returns the record data in a two-dimensional Variant array

GetString Returns the record data in a String format

Move Moves the position of the current record

MoveFirst Moves to the first record in the Recordset.MoveLast Moves to the last record in the Recordset.MoveNext Moves to the next record in the Recordset.MovePrevious Moves to the previous record in the Recordset.NextRecordset Clears any previously existing records and returns the next Recordset

The record returned is the result of the next command in a compound mand statement

com-Open Opens the Recordset.Requery Re-executes the query that generated the Recordset.Resync Retrieves the current data for the records in the Recordset.Save Writes the Recordsetcontents to a file

Seek Searches the Recordsetfor a specific string

Supports Returns a Booleanvalue indicating whether the Recordsetsupports a

particular type of functionality

Update Writes pending changes to the Recordset.UpdateBatch Submits pending changes in a Recordsetthat uses batch optimistic

updating

Collections of the Recordset Object

The Recordsetobject contains two collections: Fieldsand Properties The Fields collection is usefulfor retrieving information about the fields contained in the Recordsetobject

Trang 7

F ields Collection

The Fieldscollection contains all the Fieldobjects of a Recordsetor Recordobject Itallows you toretrieve information about the field as well as data within the field The following sections describe theproperties and methods for the Fieldscollection There are no collections for the Fieldscollection

Properties of the Fields Collection

The Fieldscollection supplies only two properties: Countand Item, which are detailed in the ing table

Recordsetobject

Item Field Identifies the position of the current record in the

Recordset

Methods of the Fields Collection

Methods for the Fieldscollection are described in the following table

Append Creates and adds a field object to the Fieldscollection

Update Finalizes any additions or deletions to the Fieldscollection

CancelUpdate Cancels any pending changes for a record

Delete Deletes a Fieldfrom the collection

Refresh Refreshes the Fieldscollection

Resync Resynchronizes the current record

F ield Object

The Fieldscollection contains Fieldobjects Each object represents an individual field within aFieldscollection from an ADO Recordor Recordsetobject

Properties of the Field Object

The properties for the Fieldobject are described in the following table

Trang 8

Property DataType Description

ActualSize Long Returns the actual size of the value of the field.Attributes Long Describes certain characteristics of the field

NumericScale Byte Number of digits allowed to the right of the

decimal point for a numeric field

OriginalValue Variant Stores the original value for the field

Status FieldStatusEnum Determines whether the field has been

success-fully added to the collection

UnderlyingValue Variant Lists the most recently retrieved value for the

field

Methods of the Field Object

The Fieldobject has two methods, which are detailed in the following table These methods apply only

to string or binary field types and may not be supported by all ADO providers

AppendChunk Allows data to be appended to a string or binary field type

GetChunk Allows retrieval of data from a string or binary field type

Collection of the Field Object

The only collection of the Fieldobject is the standard Propertiescollection

Trang 9

Record Object

The Recordobject represents a row from a Recordsetor any object returned by a data provider ARecordobject contains data from the row and allows the user to easily access that data

Properties of the Record Object

The following table describes the properties associated with a Recordobject

ActiveConnection Variant The Connectionobject used to retrieve the data

for the Record object

Mode ConnectModeEnum Specifies the permissions for modifying the

Recordobject

RecordType RecordTypeEnum Specifies the type of the Recordobject

Recordobject

State ObjectStateEnum Indicates the state of the Recordobject

Methods of the Record Object

The Recordobject has seven methods, defined in the following table

Cancel Cancels an asynchronous action on the Recordobject

Close Closes an open Recordobject

CopyRecord Copies the Recordobject to another location

DeleteRecord Deletes the current record

GetChildren Retrieves the child data associated with the Recordobject

MoveRecord Moves the Record to another location

Open Opens an existing Record or creates a new Record

Trang 10

Collections of the Record Object

The Recordobject has two collections, just like the Recordsetobject These collections are described inthe following table

Properties for the Stream Object

The following table lists the various properties of the Streamobject

stream (EOS)

LineSeparator LineSeparatorEnum Specifies the character or combination of

charac-ters used as the line separator in the stream.Mode ConnectModeEnum Specifies the permissions for modifying data in

the Streamobject

Size Long Specifies the current size of the stream of data.State ObjectStateEnum Specifies the current state of the Streamobject.Type StreamTypeEnum Specifies the type of data stored in the Stream

object

887

Appendix E: ADO Object Model Reference

Trang 11

Methods for the Stream Object

The methods you can use with the Streamobject are described in the following table

Cancel Cancels a pending asynchronous call to a Streamobject

Close Closes an open Streamobject

CopyTo Copies data from the Streamobject to another Streamobject.Flush Flushes the contents stored in the Stream’s buffer

LoadFromFile Loads the contents of a file into the Streamobject

Open Opens the Streamobject

Read Reads binary data from the stream

ReadText Reads text data from the stream

SaveToFile Writes data from the Streamobject to a file

SetEOS Sets the current position as the end of the Streamobject

SkipLine Moves to the beginning of the next line of data in the text stream.Write Appends binary data to the stream

WriteText Appends text data to the stream

Trang 12

ADO Object Argument Enumeration Infor mation

The methods supplied by the various ADO objects often have parameters that require tion options This appendix provides information about common enumerations for common ADOobject methods The information in this appendix relates to both Chapter 7 and Appendix E, andcan be used in conjunction with both

enumera-Connection.Execute Method Options

The following tables list the enumeration values that you can specify for the Command.Executemethod’s optionsargument

CommandTypeEnum Members

The CommandTypeenumeration specifies how the Connection.CommandTextargument is to beinterpreted

adCmdUnspecified -1 Hidden No command type is specified

name of a stored procedure

Trang 13

Member Value Description

adCmdUnknown 8 Default The type of command in the CommandType

argument is unknown

adCmdFile 256 The CommandTextargument is the name of a stored

recordset (Recordset.Openor Requerymethodsonly)

adCmdTableDirect 512 The CommandTextargument is the name of a table

(Recordset.Openor Requerymethods only) Thisoption cannot be combined with adAsyncExecute

ExecuteOptionEnum Members

The ExecuteOptionenumeration specifies how the provider is to execute the

Connection.CommandTextargument

adOptionUnspecified -1 Hidden The command is not specified

adAsyncExecute 16 The command executes asynchronously This option

cannot be combined with adCmdTableDirect.adAsyncFetch 32 The rows that remain to be retrieved after those

specified by the CacheSizeproperty are to beretrieved asynchronously

adAsyncFetchNonBlocking 64 The main thread never blocks while retrieving

data, so if the requested row has not beenretrieved, the current row automatically moves tothe end of the file This setting is ignored if theadCmdTableDirectoption is used, or if you open

a recordset from a stream that contains a ently stored recordset

persist-adExecuteNoRecords 128 The CommandTextargument is a command or

stored procedure that does not return records.adExecuteStream 1024 Return the results of a command operation as a

stream (Command.Executeonly)

adExecuteRecord 2048 Hidden The CommandTextargument is a

com-mand or stored procedure that returns a single row

as a Recordobject

For information about how to view hidden objects in the Object Browser, refer to Chapter 2.

Trang 14

Recordset.Open Method Options

The Openmethod of the RecordsetObject can take several different enumerations, the details of whichare described in the following tables

CursorTypeEnum Members

adOpenUnspecified -1 Hidden No cursor type is specified

adOpenForwardOnly 0 Default Specifies a forward-only cursor This is

similar to a static cursor, except that you can onlyscroll forward through the records

adOpenKeyset 1 Specifies a keyset cursor This is similar to a

dynamic cursor, except that records added by otherusers are not reflected in your recordset; however,records that other users delete are inaccessible inyour recordset

adOpenDynamic 2 Specifies a dynamic cursor In this cursor type,

all additions, deletions, and modifications made

by other users are visible in your recordset, and all types of row movement are allowed If theprovider supports bookmarks, they too areallowed

adOpenStatic 3 Specifies a static cursor This cursor type is

read-only, and additions, deletions, and modificationsmade by other users are invisible in your recordset

LockTypeEnum Members

adLockUnspecified -1 A lock type is not specified Clones are created

with the same lock type as their original

adLockPessimistic 2 Specifies pessimistic locking at record-level

adLockOptimistic 3 Specifies pessimistic locking at record-level The

record is locked only when you call the Updatemethod

adLockBatchOptimistic 4 Specifies optimistic locking for batch updated

891

Appendix F: ADO Object Argument Enumeration Information

Trang 15

Options Argument

Options arguments can be one or more of the following enumeration members

CommandTypeEnum Members

adCmdUnspecified -1 Hidden No command type is specified

stored procedure

adCmdStoredProc 4 The Sourceargument is the name of a stored

adOptionUnspecified -1 Hidden The command is not specified

adAsyncExecute 16 The command executes asynchronously This option

cannot be combined with adCmdTableDirect.adAsyncFetch 32 The rows that remain to be retrieved after those

specified by the CacheSizeproperty are to beretrieved asynchronously

adAsyncFetchNonBlocking 64 The main thread never blocks while retrieving data,

so if the requested row has not been retrieved, thecurrent row automatically moves to the end of thefile This setting is ignored if the adCmdTableDirectoption is used, or if you open a recordset from astream that contains a persistently stored recordset.adExecuteNoRecords 128 The Sourceargument is a command or stored pro-

cedure that does not return records

adExecuteStream 1024 Hidden Specifies the result of the command

execu-tion be returned as a stream Can be used only withthe Command.Executemethod

adExecuteRecord 2048 Hidden The Sourceargument is a command or

stored procedure that returns a single row as aRecordobject

Trang 16

Connection.OpenSchema Method Options

The tables in this section describe the values that can be specified for the Command.OpenSchemamethod’s SchemaandRestrictionsarguments

Schema Argument Members

The Schemaargument specifies the type of information to return, the members of which are defined inthe following table

Only those values that have meaning in Access are included The four remaining unlisted values,adSchemaActions, adSchemaCommands, adSchemaFunctions, and adSchemaSetsrelate specifically

to the Microsoft OLE DB Provider for OLAP Services library For more information about these ation members, please refer to the Microsoft Knowledge Base

enumer-SchemaEnum Members

cat-alog Unsupported by the Jet provider

from the database Unsupported by theJet provider

adSchemaCharacterSets 2 Returns the character sets defined in the

catalog Unsupported by the Jet provider.adSchemaCheckConstraints 4 Returns the check constraints (validation

rules) defined in the catalog

cat-alog Unsupported by the Jet provider.adSchemaColumnPrivileges 13 Returns the privileges on columns that are

available to, or granted by, a given user.Unsupported by the Jet provider

that are accessible to a given user

adSchemaColumnsDomainUsage 11 Returns the columns that are dependent

on a domain that is owned by a givenuser Unsupported by the Jet provider.adSchemaConstraintColumnUsage 6 Returns the columns used by referential

constraints, unique constraints, check straints, and assertions

con-Table continues on the next page

893

Appendix F: ADO Object Argument Enumeration Information

Trang 17

SchemaEnum Members (continued)

adSchemaConstraintTableUsage 7 Returns the tables that are used by

refer-ential constraints, unique constraints,check constraints, and assertions for agiven user Unsupported by the Jetprovider

cubes (multi-dimensional data) in aschema (or the catalog, if the providerdoes not support schemas) Unsupported

by the Jet provider

adSchemaDBInfoKeywords 30 Returns a list of provider-specific

key-words

adSchemaDBInfoLiterals 31 Returns a list of provider-specific literals

(quotes and escape characters) used intext commands

dimen-sions in a cube; one row per dimension.Unsupported by the Jet provider

in the catalog

hierarchies available in a cube dimension.Unsupported by the Jet provider

catalog

adSchemaKeyColumnUsage 8 Returns the columns that are defined in

the catalog as keys

available in a cube dimension

Unsupported by the Jet provider

cube measures Unsupported by the Jetprovider

cube members Unsupported by the Jetprovider

in the catalog

Trang 18

SchemaEnum Members (continued)

adSchemaProcedureColumns 29 Returns information about the columns in

stored procedures Unsupported by theJet provider

adSchemaProcedureParameters 26 Returns information about the parameters

and return codes of stored procedures.Unsupported by the Jet provider

cat-alog Unsupported by the Jet provider

properties for each level of the cubedimension Unsupported by the Jetprovider

adSchemaProviderSpecific -1 Returns schema information for a

provider that defines its own dard schema queries

non-stan-adSchemaProviderTypes 22 Returns the base data types supported by

the provider

adSchemaReferentialConstraints 9 Returns the referential constraints

(rela-tionships) defined in the catalog

that are owned by a given user

Unsupported by the Jet provider

confor-mance, options, and dialects supported inthe catalog Unsupported by the Jetprovider

adSchemaTableConstraints 10 Returns the table constraints (validation

rules) defined in the catalog

adSchemaTablePrivileges 14 Returns the privileges on tables that are

available to, or granted by, a given user.Unsupported by the Jet provider

the catalog

adSchemaTranslations 21 Returns the character translations defined

in the catalog Unsupported by the Jetprovider

Table continues on the next page

895

Appendix F: ADO Object Argument Enumeration Information

Trang 19

SchemaEnum Members

the catalog

adSchemaUsagePrivileges 15 Returns the USAGEprivileges on objects

that are available to, or granted by, a givenuser Unsupported by the Jet provider.adSchemaViewColumnUsage 24 Returns the columns included in views

Unsupported by the Jet provider

adSchemaViewTableUsage 25 Returns the tables included in views

Unsupported by the Jet provider

Restrictions Argument Members

The optional Restrictionsparameter allows the output to be filtered by specifying a member of theSchemaEnumenumeration For example, a Recordsetobject can be filtered to return only a single table

or view The available members and their constraints as described in the following table

SchemaEnum Member Restrictions

CONSTRAINT_SCHEMACONSTRAINT_NAME

CHARACTER_SET_SCHEMACHARACTER_SET_NAME

CONSTRAINT_SCHEMACONSTRAINT_NAME

COLLATION_SCHEMACOLLATION_NAME

TABLE_SCHEMATABLE_NAMECOLUMN_NAMEGRANTORGRANTEE

Trang 20

SchemaEnum Member Restrictions (continued)

TABLE_SCHEMATABLE_NAMECOLUMN_NAME

DOMAIN_SCHEMADOMAIN_NAMECOLUMN_NAMEadSchemaConstraintColumnUsage TABLE_CATALOG

TABLE_SCHEMATABLE_NAMECOLUMN_NAMEadSchemaConstraintTableUsage TABLE_CATALOG

TABLE_SCHEMATABLE_NAME

SCHEMA_NAMECUBE_NAME

SCHEMA_NAMECUBE_NAMEDIMENSION_NAMEDIMENSION_UNIQUE_NAME

PK_TABLE_SCHEMAPK_TABLE_NAMEFK_TABLE_CATALOGFK_TABLE_SCHEMAFK_TABLE_NAME

SCHEMA_NAMECUBE_NAMEDIMENSION_UNIQUE_NAMEHIERARCHY_NAME

Trang 21

SchemaEnum Member Restrictions (continued)

TABLE_SCHEMAINDEX_NAMETYPETABLE_NAME

CONSTRAINT_SCHEMACONSTRAINT_NAMETABLE_CATALOGTABLE_SCHEMATABLE_NAMECOLUMN_NAME

SCHEMA_NAMECUBE_NAMEDIMENSION_UNIQUE_NAMEHIERARCHY_UNIQUE_NAMELEVEL_NAME

LEVEL_UNIQUE_NAME

SCHEMA_NAMECUBE_NAMEMEASURE_NAMEMEASURE_UNIQUE_NAME

SCHEMA_NAMECUBE_NAMEDIMENSION_UNIQUE_NAMEHIERARCHY_UNIQUE_NAMELEVEL_UNIQUE_NAMELEVEL_NUMBERMEMBER_NAMEMEMBER_UNIQUE_NAMEMEMBER_CAPTIONMEMBER_TYPETree operator (For more information, see the OLE

DB for OLAP documentation.)

PK_TABLE_SCHEMAPK_TABLE_NAME

PROCEDURE_SCHEMAPROCEDURE_NAMECOLUMN_NAME

Trang 22

SchemaEnum Member Restrictions (continued)

PROCEDURE_SCHEMAPROCEDURE_NAMEPARAMETER_NAME

PROCEDURE_SCHEMAPROCEDURE_NAMEPROCEDURE_TYPE

SCHEMA_NAMECUBE_NAMEDIMENSION_UNIQUE_NAMEHIERARCHY_UNIQUE_NAMELEVEL_UNIQUE_NAMEMEMBER_UNIQUE_NAMEPROPERTY_TYPEPROPERTY_NAME

BEST_MATCHadSchemaReferentialConstraints CONSTRAINT_CATALOG

CONSTRAINT_SCHEMACONSTRAINT_NAME

SCHEMA_NAMESCHEMA_OWNER

TABLE_SCHEMATABLE_NAME

CONSTRAINT_SCHEMACONSTRAINT_NAMETABLE_CATALOGTABLE_SCHEMATABLE_NAMECONSTRAINT_TYPE

Table continues on the next page

899

Appendix F: ADO Object Argument Enumeration Information

Trang 23

SchemaEnum Member Restrictions (continued)

TABLE_SCHEMATABLE_NAMEGRANTORGRANTEE

TABLE_SCHEMATABLE_NAMETABLE_TYPE

TRANSLATION_SCHEMATRANSLATION_NAME

OBJECT_SCHEMAOBJECT_NAMEOBJECT_TYPEGRANTORGRANTEE

VIEW_SCHEMAVIEW_NAME

TABLE_SCHEMATABLE_NAME

VIEW_SCHEMAVIEW_NAME

Group or User SetPer missions

Method Options

The SetPermssionsmethod of both the Groupand Userobjects allows you to specify the permissions

a group or user has to a database object As noted in Chapter 7, these method options are specific toMDB database files only SetPermissions()has no effect on the Access 2007 file format (ACCDB data-base files)

Trang 24

ObjectTypeEnum Members

The ObjectTypeoption specifies the type of object to which the permission will be applied

adPermObjProviderSpecific -1 The object type is defined by the provider If

this value is specified, an ObjectTypeIDmust also be specified

ActionEnum Members

The Actionoption specifies how the permission should be applied to the specified object

adAccessGrant 1 Grant the specified permissions The permissions

speci-fied are added to those that have already been granted

adAccessSet 2 Set the specified permissions Only the specified

permis-sions will be in force

RightsEnum Members

The Rightsoption specifies the actual rights, or permissions, for denying, granting, revoking, or setting

adRightCreate 16384 The user/group has permission to create a new

object of the specified type

adRightDelete 65536 The user/group has permission to delete data from

the specified object For objects such as tables, theuser also has permission to delete data

Table continues on the next page

901

Appendix F: ADO Object Argument Enumeration Information

Trang 25

Members Value Description

from the catalog

adRightExclusive 512 The user/group has permission to access the object

permis-adRightMaximumAllowed 33554432 The user/group has the maximum number of

per-missions allowed by the provider

adRightRead -2147483648 The user/group has permission to read the object

For objects such as tables, the user also has sion to read its data

permis-adRightReadDesign 1024 The user/group has permission to read the object’s

design

adRightReadPermissions 131072 The user/group can view, but not change, the

spe-cific permissions for an object in the catalog.adRightReference 8192 The user/group has permission to reference the

object

adRightUpdate 1073741824 The user/group has permission to update the

object For objects such as tables, the user also haspermission to update its data

adRightWithGrant 4096 The user/group has permission to grant

permis-sions on the object to other users

adRightWriteDesign 2048 The user/group has permission to modify the

object’s design

adRightWriteOwner 524288 The user/group has permission to modify the

object’s owner

adRightWritePermissions 262144 The user/group has permission to modify the

spe-cific permissions for an object in the catalog

Trang 26

InheritTypeEnum Members

The Inheritoption specifies how an object inherits permissions

adInheritBoth 3 The objects and containers contained by the primary

object inherit the permissions

adInheritContainers 2 Other objects contained by the primary object also

inherit the permissions

adInheritNoPropagate 4 The adInheritObjectsand adInheritContainers

flags are not inherited

adInheritObjects 1 Objects outside the container inherit the permissions

903

Appendix F: ADO Object Argument Enumeration Information

Trang 28

The Access Object Model

By now you’ve probably read at least a few of the chapters in this book and have realized thatthere are a lot of tasks you can accomplish by programming in VBA One concept that should beabundantly clear is that to use VBA to manipulate Access, you need some knowledge about theAccess object model It was discussed briefly in Chapter 4, but as a refresher, an object model is aset of objects and collections that programmers use to manipulate a program Microsoft Access has

a rich object model You’ll use that to manipulate forms, reports, queries, macros, and other ponents of the Access interface

com-Much of the information in this appendix can also be found in some form within the Access VisualBasic Reference Help file

The Application Object

All of the Access objects you’ll manipulate within code are children of the Applicationobject,which is the parent object for all objects and collections in the Access object model Every objectand collection is related to the Applicationobject through either a direct parent/child relation-ship or multiple parent/child relationships Figure G-1 shows the Access objects and collectionsthat are the direct children of the Applicationobject The Office 12.0 object library exposesobjects from the Application object for each Office application Because those objects are part of the Office object model, they aren’t listed here

The Applicationobject refers to the currently active Access application It contains all MicrosoftAccess objects and collections You can use the Applicationobject to apply methods or set prop-erties for the entire Access application For example, you can use the object’s SetOptionmethod

to control just about all the settings visible in the Access Options dialog box The various settingsyou can use with SetOptionare listed a little later in this appendix The following code displayshidden objects in the navigation pane:

Trang 29

Figure G-1

Nearly all code you write in Access utilizes the Applicationobject somewhere within the code

Application Object Properties

The following table lists the various properties of the Applicationobject It contains not only stringand Boolean properties, but also properties that refer to other objects within the Access object model.Those objects are discussed later in this appendix

AnswerWizard AnswerWizardobject Used to reference the current AnswerWizard

object

Application Applicationobject Returns the current Access Application object

For example, Me.Application on a form orreport

Assistance IAssistanceobject Returns an IAssistance object that can be used

for programmatic searching of Access help.Assistant Assistantobject Returns the Office Assistant object This object

has been deprecated in Office 2007

AutoCorrect AutoCorrectobject Returns an AutoCorrect object that represents

the AutoCorrect settings for the specified trol

con-AutomationSecurity MsoAutomationSecurity Returns or sets an MsoAutomationSecurity

con-stant that represents the security mode Access useswhen opening files

BrokenReference Boolean True if the current database has any broken

refer-ences to databases or type libraries

Trang 30

Property Data Type Description

Access

CodeContextObject Object Determines the object in which a macro or VBA

code is executing

CodeProject CodeProject Accesses the CodeProject object

COMAddIns COMAddInscollection References the current COMAddIns collection

object

CommandBars CommandBarscollection References the CommandBars collection

CurrentData CurrentDataobject Used to access the CurrentData object

CurrentObjectName String Name of the active database object

CurrentObjectType AcObjectTypeEnum Intrinsic constant used to determine the type of the

active database object See the Object Browser forpossible values

CurrentProject CurrentProjectobject Accesses the CurrentProject object

DBEngine DBEngineobject Returns the instance of the Access database engine

and its related properties and collections

DoCmd DoCmdobject Returns the DoCmd object that contains many

meth-ods commonly used in Access

FeatureInstall MsoFeatureInstall Determines or specifies how Access handles calls to

methods or properties not yet installed

FileDialog FileDialogobject Represents a common File dialog box such as the

Open, Save As, or Browse Folder dialog box

FileSearch FileSearchobject This object has been deprecated in Office 2007 You

should use the FileSystemObject instead

Forms Formscollection Returns the collection of open forms in a database.IsCompiled Boolean True if the current Visual Basic project is in a com-

piled state

LanguageSettings LanguageSettingsobject Returns a reference to the LanguageSettings

object Can be used to determine the user-interfacelanguage for the running instance of Access

MacroError MacroErrorobject Returns an instance of the MacroError object

Represents errors raised from Access macros

database

907

Appendix G: The Access Object Model

Table continues on the next page

Trang 31

Property Data Type Description

Modules Modulescollection Returns the collection of open modules in a

Parent Applicationobject Because the Application object is the highest

object in the hierarchy, Parent returns the currentApplicationobject

Printer Printerobject Returns or sets a Printer object representing the

default printer on the current computer

Printers Printerscollection Returns the printers installed on the current

computer

ProductCode String Returns the globally unique identifier (GUID) for

the Access application

References Referencescollection Returns the collection of References for the current

database

Reports Reportscollection Returns the collection of open reports in a database

ShortcutMenuBar String Specifies the shortcut menu that appears when you

right-click on a form, report, or control

TempVars TempVarscollection Returns an instance of the TempVars collection

Can be used to maintain temporary data in a tion and pass data between Access macros andVBA code

collec-UserControl Boolean Determines whether the current Access instance

was launched via automation

VBE VBEobject Returns an instance of the Visual Basic Editor

Visible Boolean Returns True if the Access window is visible

Application Object Methods

The following table lists all of the methods available from the Applicationobject Any arguments forthe methods are also listed For example, you can use the CompactRepairmethod of the Applicationobject with the following code:

Application.CompactRepair “C:\DB\Samples.mdb”, “C:\DB\SamplesCompacted.mdb”

Trang 32

Method Arguments Description

with an Access or DAO error number

as a hyperlink address to the Favoritesfolder

would appear in the query design grid,

in Filter By Form or Server Filter ByForm mode

library database or add-in

Append-Only memo field Valid forACCDB files only

database Set LogFile to True torecord any corruption found to a log file

one version to another

CreateAccessProject FilePath, Connect Creates a new Access Data Project

(ADP) Specify the Connect argument

to set the ConnectionString for theproject

that can be used to export related data

to XML with the ExportXML method

cur-rently open in Design view Returns aControlobject

CreateForm Database, FormTemplate Creates a new form in Design view and

returns a Form object

file (MDW)

Path, Name, Company,WorkgroupID, Replace

ReportName, Expression,Header, Footer,

FormName, ControlType,Section, Parent, ColumnName,Left, Top, Width, Height

SourceFileName,DestinationFileName,DestinationFileFormat

SourceFile,DestinationFile,LogFile

TableName, ColumnName,QueryString

Field, FieldType,Expression

909

Appendix G: The Access Object Model

Table continues on the next page

Trang 33

Method Arguments Description

CreateReport Database, ReportTemplate Creates a new report in design view

and returns a Report object

cur-rently open in design view

represents the currently open database

the database Used with user-level rity in MDB files

secu-DAvg Expr, Domain, Criteria Calculates the average of a set of values

in a specified set of records (Domain).DCount Expr, Domain, Criteria Determines the number of records

within a set of records

DDEExecute ChanNum, Command Sends a command from a client

applica-tion to a server applicaapplica-tion

Exchange) channel between two applications

DDEPoke ChanNum, Item, Data Supplies text data from a client

applica-tion to a server applicaapplica-tion over anopen DDE channel

channel

with-out requiring the user to log on again.DeleteControl FormName, ControlName Deletes a control on a specified form.DeleteReportControl ReportName, ControlName Deletes a control on a specific report.DFirst Expr, Domain, Criteria Returns the first record from a particu-

lar field in a table or query Because sortorder can change, the first record is typ-ically not guaranteed

DLast Expr, Domain, Criteria Returns the first record from a

particu-lar field in a table or query Because sortorder can change, the last record is typi-cally not guaranteed

ReportName, ControlType,Section, Parent,

ColumnName, Left, Top,Width, Height

Trang 34

Method Arguments Description

DLookup Expr, Domain, Criteria Gets the value from a particular field

from a specified set of records

specified set of records

specified set of records

DStDev Expr, Domain, Criteria Estimates the standard deviation across a

set of values in a set of records The dard deviation is calculated for a sample.DStDevP Expr, Domain, Criteria Estimates the standard deviation across

stan-a set of vstan-alues in stan-a set of records Thestandard deviation is calculated for thepopulation

DSum Expr, Domain, Criteria Calculates the sum of a set of values in

a set of records

DVar Expr, Domain, Criteria Estimates the variance across a set of

values in a set of records The variation

is calculated for a sample

DVarP Expr, Domain, Criteria Estimates variance across a set of values

in a set of records The variance is culated for the population

cal-Echo EchoOn, bstrStatusBarText Specifies whether Access repaints the

display screen

Euro to a participating currency Youcan also use it to convert a numberfrom one participating currency toanother by using the Euro as an inter-mediary (triangulation)

text string or numeric value

navigation pane to XML Includes tom categories and groups

schemas, and presentation information

ObjectType, DataSource,DataTarget, SchemaTarget,PresentationTarget,ImageTarget, Encoding,OtherFlags, WhereCondition,AdditionalData

Number, SourceCurrency,TargetCurrency,FullPrecision,TriangulationPrecision

911

Appendix G: The Access Object Model

Table continues on the next page

Trang 35

Method Arguments Description

spec-ified by a hyperlink

GetHiddenAttribute ObjectType, ObjectName Determines whether the specified object

is hidden in the navigation pane

in the Options dialog box

HTMLEncode PlainText, Length Returns HTML encoded text for data

Can be used to set data in Rich Textmemo fields

main Access window by MicrosoftWindows

HyperlinkPart Hyperlink, Part Returns information about data stored

as a hyperlink data type

ImportNavigationPane Path, fAppendOnly Imports navigation pane data that was

exported withExportNavigationPane.ImportXML DataSource, ImportOptions Allows import of XML data and/or

schema information

LoadCustomUI CustomUIName, CustomUIXML Loads custom ribbon extensibility XML

control

NewAccessProject FilePath, Connect Creates and sets a new ADP as the

active data project

or MDB) in the Access window Canalso create a new database from anAccess template

another value when a value is null.OpenAccessProject FilePath, Exclusive Opens an ADP as the current Access

project

database

FilePath, Exclusive,bstrPassword

Address, SubAddress,NewWindow, AddHistory,ExtraInfo, Method,HeaderInfo

Filepath, FileFormat,Template, SiteAddress,ListID

Trang 36

Method Arguments Description

PlainText RichText, Length Returns unformatted text for the

speci-fied rich text

object has been created

AppTitleor AppIcon has beenchanged via code

function

com-mand

SetDefaultWorkgroupFile Path Sets the default Workgroup file to the

file specified in the Path argument

speci-fied object in the navigation pane.SetOption OptionName, Setting Sets the current value of an option in

the Options dialog box The variousOptionNamearguments are detailed atthe end of this appendix

specified text in the status bar, (2)return information about Access and itsassociated files, or (3) return the state of

a current database object

Language (XSL) stylesheet to an XMLdata file and writes the XML to an XML data file

DataSource,TransformSource,OutputTarget,WellFormedXMLOutput,ScriptOption

Action, Argument2,Argument3

ObjectType,ObjectName, fHidden

Procedure(up to 30 optionalarguments can also follow)

913

Appendix G: The Access Object Model

Trang 37

AllObjects Collection

Access contains a hidden collection called the AllObjects collection Chances are you’ll never use this lection directly, but it happens to be the parent object of several collections that are commonly used.These collections are:

AllDatabaseDiagrams Contains an object for each database diagram in a SQL Server database

Applies to ADP files only

AllForms Contains an object for each form in a database or project file

AllFunctions Contains an object for each user-defined function in a SQL Server database

Applies to ADP files only

AllMacros Contains an object for each macro in a database or project file

AllModules Contains an object for each module in a database or project file

AllQueries Contains an object for each query in an Access database (ACCDB

or MDB)

AllReports Contains an object for each report in a database or project file

AllStoredProcedures Contains an object for each stored procedure in a SQL Server database

Applies to ADP files only

AllTables Contains an object for each table in a database or project file

AllViews Contains an object for each view in a SQL Server database Applies to ADP

files only

Each of these collections contains AccessObjectobjects that are described in a later section Becausethese collections all derive from the AllObjectscollection, they have the same properties and methods.For example, take a closer look at the AllFormscollection

As its name implies, the AllFormscollection contains an Access object for each form in the

CurrentProjector CodeProjectobject It contains the typical collection properties of Application,Count, Item, and Parent Many of the other collections listed in this appendix have the same set ofproperties, which are described in the following table

Application Applicationobject Returns the Application object associated with the

current collection

Item AccessObject Returns a specific member of the collection by

posi-tion or index

Parent Object Returns the parent object of the current collection

Trang 38

The Cur rentData Object

The CurrentDataobject is used to refer to objects stored within the current database by the serverapplication (Access database engine or SQL) It has a variety of properties, described in the followingtable, that you can manipulate as well as several collections of its own

AllDatabaseDiagrams AllDatabaseDiagramscollection Represents the collection of database

diagrams in the SQL Server database.AllFunctions AllFunctionscollection Represents all the user-defined func-

tions in the SQL Server database.AllQueries AllQueriescollection Represents all of the queries defined

in the database This collection isempty in ADP files

AllStoredProcedures AllStoredProcedurescollection References all of the stored

proce-dures in the database

AllTables AllTablescollection References all the tables in the

database

AllViews AllViewscollection References all views in the database

The Cur rentProject Object

The CurrentProjectobject represents the Access project for the database or project that is currentlyopen in Access The Access project consists of the non-data items such as Forms, Reports, Macros, andModules The CurrentProjectobject has several collections and a number of properties you can usewithin your application Here are descriptions of those properties:

AccessConnection Connection Returns a reference to the currently active ADO

Connectionobject

AllForms AllFormscollection Returns a reference to the AllForms collection

and its associated properties

AllMacros AllMacroscollection Returns a reference to the AllMacros collection

and its associated properties

AllModules AllModulescollection Returns a reference to the AllModules

collec-tion and its associated properties

AllReports AllReportscollection Returns a reference to the AllReports

collec-tion and its associated properties

915

Appendix G: The Access Object Model

Table continues on the next page

Trang 39

Property Data Type Description

Application Applicationobject Returns a reference to the current Application

object

BaseConnectionString String Returns the base Connection String for the

CurrentProjector CodeProjectobject.Connection Connectionobject Returns the currently active ADO Connection

object

FileFormat AcFileFormatEnum Returns a constant representing the Microsoft

Access version of the specified project

CurrentProjectobject

Returns the collection of import and export ifications in the database

spec-IsConnected Boolean Determines if the CurrentProject is currently

connected to a data source

IsTrusted Boolean Returns True if the current database is opened in

enabled mode and can execute code

Parent Applicationobject For the CodeProject object, the Parent

prop-erty returns the associated Application object

Access database (.mdb) or Access project (.adp).ProjectType AcProjectTypeEnum Determines the type of project currently open

through the CurrentProject object

Properties Propertiescollection Returns a reference to the entire Properties

collection for the CurentProject object.Boolean True if user information is removed from the

specified project False if user information isstored within the project

The following table describes the CurrentProjectobject’s methods

CloseConnection None Closes the current connection between the

CurrentProjectobject and the database specified

in the project’s base connection string

ImportExport Specificationscollection

-RemovePersonal

Information

ImportExport

Specifications

Trang 40

Method Arguments Description

OpenConnection Opens an ADO Connection to an existing Access

proj-ect (.adp) or Access database (.accdb, mdb) as thecurrent Access project or database

UpdateDependencyInfo None Updates the dependency information for the

database

You’ve probably noticed that there is some overlap between several objects or methods in the Access andDAO object models, specifically CurrentProjectand CodeProject, CurrentDataand CodeData,and CurrentDband CodeDb Each pair of objects contains the same properties and methods so that theyare interchangeable

Given that they have the same interfaces, how do you know which one to use and when? The shortanswer is that the Codeobjects and methods are used to refer to objects in a referenced or add-in data-

base, which are also known as library databases because you can call code from them like a code library.

Naturally, the Currentobjects are used to refer to objects in the file that is open in the Access user face For example, if you have a database called Samples.mdb, and that database contains a reference to

inter-a dinter-atinter-abinter-ase cinter-alled VBASamples.mdb, the current database would be Samples.mdband the code databasewould be VBASamples.mdb while code is executing in VBASamples.mdb When code is running inSamples.mdb, the current and the code database both refer to Samples.mdb

The following table summarizes some of the differences

queries, and sets in the currentdatabase

queries, and sets in a library database

AccessObjectobjects for Accessproject items in thecurrent database

AccessObjectobjects for Accessproject items in alibrary database

AllForms, AllMacros,AllModules, AllReports

AllForms, AllMacros,AllModules, AllReports

BaseConnection String, UserID,Password

-917

Appendix G: The Access Object Model

Table continues on the next page

Ngày đăng: 09/08/2014, 12:22

TỪ KHÓA LIÊN QUAN