100% found this document useful (1 vote)
4K views

Instant Microsoft Access 2013 Programming by Example with VBA XML and ASP 1st Edition Julitta Korol ebook download PDF full chapters

The document provides information about the book 'Microsoft Access 2013 Programming by Example with VBA, XML, and ASP' by Julitta Korol, including details on how to download it and related ebooks. It outlines the book's content structure, covering various aspects of VBA programming, including procedures, variables, error handling, and data access technologies. Additionally, it includes licensing and warranty information from the publisher, Mercury Learning and Information LLC.

Uploaded by

yulleilani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
4K views

Instant Microsoft Access 2013 Programming by Example with VBA XML and ASP 1st Edition Julitta Korol ebook download PDF full chapters

The document provides information about the book 'Microsoft Access 2013 Programming by Example with VBA, XML, and ASP' by Julitta Korol, including details on how to download it and related ebooks. It outlines the book's content structure, covering various aspects of VBA programming, including procedures, variables, error handling, and data access technologies. Additionally, it includes licensing and warranty information from the publisher, Mercury Learning and Information LLC.

Uploaded by

yulleilani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Visit https://ebookultra.

com to download the full version and


explore more ebooks

Microsoft Access 2013 Programming by Example


with VBA XML and ASP 1st Edition Julitta Korol

_____ Click the link below to download _____


https://ebookultra.com/download/microsoft-
access-2013-programming-by-example-with-vba-xml-and-
asp-1st-edition-julitta-korol/

Explore and download more ebooks at ebookultra.com


Here are some suggested products you might be interested in.
Click the link to download

XML Programming Web Applications and Web Services With JSP


and ASP 1st Edition Alexander Nakhimovsky

https://ebookultra.com/download/xml-programming-web-applications-and-
web-services-with-jsp-and-asp-1st-edition-alexander-nakhimovsky/

Microsoft Access 2013 Illustrated Brief 1st Edition Lisa


Friedrichsen

https://ebookultra.com/download/microsoft-access-2013-illustrated-
brief-1st-edition-lisa-friedrichsen/

Access 2007 VBA Programming For Dummies 1st Edition Joseph


C. Stockman

https://ebookultra.com/download/access-2007-vba-programming-for-
dummies-1st-edition-joseph-c-stockman/

Applied XML programming for Microsoft NET 1st Edition Dino


Esposito

https://ebookultra.com/download/applied-xml-programming-for-microsoft-
net-1st-edition-dino-esposito/
Korn shell programming by example 1st Edition Dennis
O'Brien

https://ebookultra.com/download/korn-shell-programming-by-example-1st-
edition-dennis-obrien/

Programming Language Fundamentals by Example 1st Edition


D.E. Stevenson

https://ebookultra.com/download/programming-language-fundamentals-by-
example-1st-edition-d-e-stevenson/

Access 2007 VBA bible for data centric Microsoft Office


applications 1st Edition Helen Feddema

https://ebookultra.com/download/access-2007-vba-bible-for-data-
centric-microsoft-office-applications-1st-edition-helen-feddema/

Excel Programming with VBA Starter 1st Edition Robert


Martin

https://ebookultra.com/download/excel-programming-with-vba-
starter-1st-edition-robert-martin/

Cocoon 2 Programming Web Publishing with XML and Java 1st


Edition Bill Brogden

https://ebookultra.com/download/cocoon-2-programming-web-publishing-
with-xml-and-java-1st-edition-bill-brogden/
Microsoft Access 2013 Programming by Example with
VBA XML and ASP 1st Edition Julitta Korol Digital
Instant Download
Author(s): Julitta Korol
ISBN(s): 9781938549496, 193854949X
Edition: 1
File Details: PDF, 56.58 MB
Year: 2014
Language: english
MICROSOFT® ACCESS® 2013
PROGRAMMING BY EXAMPLE
LICENSE, DISCLAIMER OF LIABILITY, AND LIMITED WARRANTY
By purchasing or using this book (the “Work”), you agree that this license
grants permission to use the contents contained herein, but does not give you
the right of ownership to any of the textual content in the book or ownership
to any of the information or products contained in it. This license does not
permit uploading of the Work onto the Internet or on a network (of any kind)
without the written consent of the Publisher. Duplication or dissemination
of any text, code, simulations, images, etc. contained herein is limited to and
subject to licensing terms for the respective products, and permission must
be obtained from the Publisher or the owner of the content, etc., in order to
reproduce or network any portion of the textual material (in any media) that is
contained in the Work.

MERCURY LEARNING AND INFORMATION LLC (“MLI” or “the Publisher”) and anyone
involved in the creation, writing, or production of the companion disc, accom-
panying algorithms, code, or computer programs (“the software”), and any
accompanying Web site or software of the Work, cannot and do not warrant
the performance or results that might be obtained by using the contents of the
Work. The author, developers, and the Publisher have used their best efforts to
insure the accuracy and functionality of the textual material and/or programs
contained in this package; we, however, make no warranty of any kind, express
or implied, regarding the performance of these contents or programs. The
Work is sold “as is” without warranty (except for defective materials used in
manufacturing the book or due to faulty workmanship).

The author, developers, and the publisher of any accompanying content, and
anyone involved in the composition, production, and manufacturing of this
work will not be liable for damages of any kind arising out of the use of (or the
inability to use) the algorithms, source code, computer programs, or textual
material contained in this publication. This includes, but is not limited to, loss
of revenue or profit, or other incidental, physical, or consequential damages
arising out of the use of this Work.

The sole remedy in the event of a claim of any kind is expressly limited to
replacement of the book, and only at the discretion of the Publisher. The use
of “implied warranty” and certain “exclusions” vary from state to state, and
might not apply to the purchaser of this product.
MICROSOFT® ACCESS® 2013
PROGRAMMING BY EXAMPLE
with VBA, XML, and ASP

Julitta Korol

Mercury Learning and Information


Dulles, Virginia
Boston, Massachusetts
New Delhi
Copyright ©2014 by Mercury Learning and Information LLC. All rights reserved.

This publication, portions of it, or any accompanying software may not be reproduced in any
way, stored in a retrieval system of any type, or transmitted by any means, media, electronic display
or mechanical display, including, but not limited to, photocopy, recording, Internet postings, or
scanning, without prior permission in writing from the publisher.

Publisher: David Pallai


Mercury Learning and Information
22841 Quicksilver Drive
Dulles, VA 20166
info@merclearning.com
www.merclearning.com
1-800-758-3756

This book is printed on acid-free paper.

Julitta Korol. Microsoft Access 2013 Programming by Example with VBA, XML, and ASP.
ISBN: 978-1-938549-80-9

The publisher recognizes and respects all marks used by companies, manufacturers, and
developers as a means to distinguish their products. All brand names and product names
mentioned in this book are trademarks or service marks of their respective companies. Any
omission or misuse (of any kind) of service marks or trademarks, etc. is not an attempt to
infringe on the property of others.

Library of Congress Control Number: 2013958001

141516321

Our titles are available for adoption, license, or bulk purchase by institutions, corporations, etc.
For additional information, please contact the Customer Service Dept. at 1-800-758-3756 (toll free).

The sole obligation of Mercury Learning and Information to the purchaser is to replace the
disc, based on defective materials or faulty workmanship, but not based on the operation or
functionality of the product.
To my husband, Paul, and my parents-in-law, Alfreda and Piotr Korol.
They’ve been my biggest fans since the first edition of this book.
I am thankful for their love and support.
CONTENTS

Dedication .................................................................................................... v
Acknowledgments ..................................................................................... xxv
Introduction ............................................................................................ xxvii

PART 1—INTRODUCTION TO ACCESS 2013 VBA PROGRAMMING

Chapter 1 Writing Procedures in Modules .........................................3


Procedure Types ...................................................................................................4
Module Types ........................................................................................................7
Standard Modules ............................................................................................7
Writing Procedures in a Standard Module ..............................................7
Executing Your Procedures and Functions .......................................... 10
Class Modules ............................................................................................... 12
Events, Event Properties, and Event Procedures ........................................... 14
Why Use Events?........................................................................................... 16
Walking Through an Event Procedure ...................................................... 16
Compiling Your Procedures ........................................................................ 22
Placing a Database in a Trusted Location ...................................................... 22
Chapter Summary ............................................................................................. 25

Chapter 2 Exploring the Visual Basic Editor (VBE).........................27


Understanding the Project Explorer Window ............................................... 28
Understanding the Properties Window.......................................................... 29
Understanding the Code Window .................................................................. 31
Other Windows in the VBE ............................................................................. 33
Assigning a Name to the VBA Project ............................................................ 34
Renaming the Module ...................................................................................... 35
viii C ONTENTS

On-the-Fly Syntax and Programming Assistance ......................................... 35


List Properties/Methods .............................................................................. 36
Parameter Info .............................................................................................. 37
List Constants ................................................................................................ 38
Quick Info ...................................................................................................... 39
Complete Word ............................................................................................. 40
Indent/Outdent ............................................................................................. 40
Comment Block/Uncomment Block ......................................................... 41
Using the Object Browser ................................................................................. 42
Using the VBA Object Library......................................................................... 44
Using the Immediate Window ......................................................................... 46
Chapter Summary ............................................................................................. 48

Chapter 3 Using Variables, Data Types, and Constants ...................49


What are Data Types? ....................................................................................... 50
What Are Variables? .......................................................................................... 52
Creating Variables ............................................................................................. 53
Declaring Variables ........................................................................................... 54
Specifying the Data Type of a Variable ........................................................... 58
Using Type Declaration Characters ................................................................ 59
Assigning Values to Variables .......................................................................... 60
Forcing Declaration of Variables ..................................................................... 63
Understanding the Scope of Variables ............................................................ 65
Procedure-Level (Local) Variables ............................................................. 66
Module-Level Variables ............................................................................... 66
Project-Level Variables ................................................................................ 69
Understanding the Lifetime of Variables........................................................ 70
Understanding and Using Temporary Variables ........................................... 70
Creating a Temporary Variable with a TempVars
Collection Object ..................................................................................... 71
Retrieving Names and Values of TempVar Objects ................................. 72
Using Temporary Global Variables in Expressions .................................. 73
Removing a Temporary Variable from a TempVars
Collection Object ..................................................................................... 73
Understanding and Using Static Variables ..................................................... 74
Understanding and Using Object Variables ................................................... 76
Disposing of Object Variables ..................................................................... 78
CONTENTS ix

Finding a Variable Definition .......................................................................... 78


Determining the Data Type of a Variable....................................................... 79
Using Constants in VBA Procedures .............................................................. 80
Intrinsic Constants ............................................................................................ 81
Grouping Constants with the Enum Type ..................................................... 83
Chapter Summary ............................................................................................. 85

Chapter 4 Passing Arguments to Procedures and


Functions ..........................................................................87
Writing a Function Procedure ......................................................................... 88
Specifying the Data Type for a Function’s Result .......................................... 90
Passing Arguments by Reference and by Value ............................................. 92
Using Optional Arguments .............................................................................. 94
Using the IsMissing Function .......................................................................... 95
Built-in Functions ............................................................................................. 96
Using the MsgBox Function ............................................................................ 97
Returning Values from the MsgBox Function ........................................105
Using the InputBox Function ........................................................................107
Converting Data Types ...................................................................................109
Using Master Procedures and Subprocedures .............................................112
Chapter Summary ...........................................................................................116

PART 2—CONTROLLING PROGRAM EXECUTION

Chapter 5 Decision Making with VBA............................................119


Relational and Logical Operators ..................................................................120
If…Then Statement .........................................................................................121
Multi-Line If…Then Statement .....................................................................123
Decisions Based on More Than One Condition..........................................124
If…Then…Else Statement ..............................................................................126
If…Then…ElseIf Statement ...........................................................................129
Nested If…Then Statements ..........................................................................130
Select Case Statement......................................................................................133
Using Is with the Case Clause ...................................................................136
Specifying a Range of Values in a Case Clause .......................................136
Specifying Multiple Expressions in a Case Clause .................................138
Chapter Summary ...........................................................................................139
x C ONTENTS

Chapter 6 Repeating Actions in VBA .............................................141


Using the Do…While Statement ...................................................................142
Another Approach to the Do…While Statement........................................144
Using the Do…Until Statement .....................................................................145
Another Approach to the Do…Until Statement .........................................147
For…Next Statement.......................................................................................148
For Each…Next Statement .............................................................................151
Exiting Loops Early .........................................................................................152
Nested Loops ....................................................................................................153
Chapter Summary ...........................................................................................155

PART 3—KEEPING TRACK OF MULTIPLE VALUES

Chapter 7 Working with Arrays ......................................................159


What Is an Array? ............................................................................................160
Declaring Arrays..............................................................................................162
Array Upper and Lower Bounds ...................................................................163
Initializing an Array ........................................................................................164
Filling an Array Using Individual Assignment
Statements ...........................................................................................164
Filling an Array Using the Array Function .............................................165
Filling an Array Using the For…Next Loop............................................165
Using Arrays in VBA Procedures ..................................................................166
Arrays and Looping Statements ....................................................................168
Using a Two-Dimensional Array...................................................................172
Static and Dynamic Arrays ............................................................................173
Array Functions ...............................................................................................175
The Array Function ....................................................................................176
The IsArray Function .................................................................................176
The Erase Function ....................................................................................177
The LBound and UBound Functions ......................................................179
Errors in Arrays ...............................................................................................180
Parameter Arrays .............................................................................................182
Passing Arrays to Function Procedures........................................................183
Sorting an Array ..............................................................................................184
Chapter Summary ...........................................................................................186
CONTENTS xi

Chapter 8 Working with Collections and Class Modules...............187


Working with Collections ..............................................................................188
Declaring a Custom Collection ................................................................190
Adding Objects to a Custom Collection ..................................................190
Removing Objects from a Custom Collection ........................................192
Creating Custom Objects ...............................................................................193
Creating a Class...........................................................................................193
Variable Declarations .................................................................................194
Defining the Properties for the Class .......................................................195
Creating the Property Get Procedures ................................................197
Creating the Property Let Procedures.................................................197
Creating the Class Methods ......................................................................199
Creating an Instance of a Class .................................................................200
Event Procedures in the Class Module ....................................................201
Creating the User Interface ............................................................................202
Running the Custom Application .................................................................213
Watching the Execution of Your VBA Procedures .....................................214
Chapter Summary ...........................................................................................216

PART 4—ERROR HANDLING AND DEBUGGING

Chapter 9 VBE Tools for Testing and Debugging ...........................219


Testing VBA Procedures.................................................................................221
Stopping a Procedure ......................................................................................221
Using Breakpoints.......................................................................................222
Removing Breakpoints ..........................................................................227
Using the Immediate Window in Break Mode .......................................228
Using the Stop Statement ...........................................................................229
Using the Assert Statement .......................................................................230
Using the Add Watch Window .................................................................231
Removing Watch Expressions ..............................................................236
Using Quick Watch.....................................................................................236
Using the Locals Window...............................................................................237
Understanding the Call Stack Dialog Box....................................................238
Stepping Through VBA Procedures ..............................................................239
Stepping Over a Procedure ........................................................................240
Stepping Out of a Procedure .....................................................................242
xii C ONTENTS

Running a Procedure to Cursor ................................................................242


Setting the Next Statement .............................................................................242
Showing the Next Statement ..........................................................................243
Stopping and Resetting VBA Procedures .....................................................243
Chapter Summary ...........................................................................................243

Chapter 10 Conditional Compilation and Error Trapping ............245


Understanding and Using Conditional Compilation .................................246
Navigating with Bookmarks ..........................................................................249
Trapping Errors................................................................................................250
Using the Err Object .......................................................................................251
Procedure Testing ............................................................................................255
Setting Error Trapping Options in Your Visual Basic Project ...................257
Chapter Summary ...........................................................................................258

PART 5—ACCESS VBA PROGRAMMING WITH DAO AND ADO

Chapter 11 Data Access Technologies in Microsoft Access ............261


Understanding Database Engines: Jet/ACE .................................................262
Understanding Access Versions and File Formats ......................................263
Understanding Library References ...............................................................266
Overview of Object Libraries in Microsoft Access .....................................269
The Visual Basic for Applications Object Library (VBA) .....................269
The Microsoft Access 15.0 Object Library ..............................................269
The Microsoft Office 15.0 Access Database Engine Object Library ....269
The Microsoft DAO 3.6 Object Library...................................................269
The Microsoft ActiveX Data Objects 6.1 Library (ADO) .....................271
Creating a Reference to the ADO Library....................................................273
Understanding Connection Strings ..............................................................274
Using ODBC Connection Strings .................................................................276
Creating and Using ODBC DSN Connections .......................................276
Creating and Using DSN-less ODBC Connections ...............................281
Using OLE DB Connection Strings ..............................................................283
Connection String via a Data Link File ........................................................284
Opening Microsoft Access Databases ...........................................................287
Opening a Microsoft Jet Database in Read/Write Mode with DAO....287
Opening a Microsoft Jet Database in Read/Write Mode with ADO ...290
CONTENTS xiii

Opening a Microsoft Access Database in Read-Only


Mode with DAO .................................................................................294
Opening a Microsoft Jet Database in Read-Only Mode with ADO ....294
Opening a Microsoft Jet Database Secured with a Password ...............294
Opening a Microsoft Jet Database with User-Level Security................299
Connecting to the Current Access Database ...............................................302
Opening Other Databases, Spreadsheets, and
Text Files from Access 2013 ..................................................................304
Connecting to an SQL Server Database ..................................................304
Opening a Microsoft Excel Workbook ....................................................304
Opening a Text File Using ADO...............................................................309
Creating a New Access Database ...................................................................311
Creating a Database with DAO.................................................................311
Creating a Database with ADO ................................................................312
Copying a Database.........................................................................................314
Copying a Database with DAO .................................................................314
Copying a Database with FileSystemObject ...........................................316
Database Errors ...............................................................................................317
Compacting a Database ..................................................................................320
Chapter Summary ...........................................................................................322

Chapter 12 Creating and Accessing Database


Tables and Fields .......................................................... 323
Creating a Microsoft Access Table and Setting Field
Properties (DAO Method) .............................................................................324
Creating a Microsoft Access Table and Setting Field
Properties (ADO Method) .............................................................................330
Copying a Table ...............................................................................................333
Deleting a Database Table ..............................................................................335
Adding New Fields to an Existing Table.......................................................336
Creating Calculated Fields .............................................................................338
Creating Multivalue Lookup Fields with DAO ...........................................341
Creating Attachment Fields with DAO ........................................................344
Creating Append Only Memo Fields with DAO .........................................346
Creating Rich Text Memo Fields with DAO ................................................353
Removing a Field from a Table ......................................................................356
Retrieving Table Properties ............................................................................357
Retrieving Field Properties ............................................................................359
xiv C ONTENTS

Linking a Microsoft Access Table ..................................................................360


Linking a dBASE Table ...................................................................................362
Linking a Microsoft Excel Worksheet...........................................................362
Listing Database Tables...................................................................................365
Listing Tables and Fields.................................................................................366
Listing Data Types ...........................................................................................368
Changing the AutoNumber ...........................................................................368
Chapter Summary ...........................................................................................370

Chapter 13 Setting Up Primary Keys, Indexes,


and Table Relationships ............................................371
Creating a Primary Key Index .......................................................................372
Creating Indexes Using ADO ........................................................................372
Creating Indexes Using DAO ........................................................................374
Creating a Single-Field Index Using ADO...................................................376
Adding a Multiple-Field Index to a Table Using DAO ...............................379
Listing Indexes in a Table ...............................................................................380
Deleting Table Indexes ....................................................................................382
Creating Table Relationships Using ADO....................................................383
Chapter Summary ...........................................................................................386

Chapter 14 Finding and Reading Records ......................................387


Introduction to DAO Recordsets ..................................................................388
Opening Various Types of Recordsets .....................................................389
Opening a Snapshot and Counting Records ...........................................391
Retrieving the Contents of a Specific Field in a Table ...........................393
Moving between Records in a Table.........................................................394
Finding Records in a Table-Type Recordset ...........................................395
Finding Records in Dynasets or Snapshots .............................................397
Finding the nth Record in a Snapshot .......................................................399
Introduction to ADO Recordsets ..................................................................401
Cursor Types ...............................................................................................402
Lock Types ...................................................................................................404
Cursor Location ..........................................................................................405
The Options Parameter..............................................................................406
Opening a Recordset ..................................................................................409
Opening a Recordset Based on a Table or Query ..............................411
Opening a Recordset Based on an SQL Statement ............................416
CONTENTS xv

Opening a Recordset Based on Criteria..............................................417


Opening a Recordset Directly ..............................................................418
Moving Around in a Recordset.................................................................419
Finding the Record Position......................................................................420
Reading Data from a Field.........................................................................421
Returning a Recordset as a String.............................................................422
Finding Records Using the Find Method ................................................424
Finding Records Using the Seek Method ................................................426
Finding a Record Based on Multiple Conditions ...................................428
Using Bookmarks ............................................................................................429
Using Bookmarks to Filter a Recordset ..........................................431
Using the GetRows Method to Fill the Recordset ..................................433
Chapter Summary ...........................................................................................434

Chapter 15 Working with Records ..................................................435


Adding a New Record with DAO ..................................................................436
Adding a New Record with ADO .................................................................438
Adding Attachments .......................................................................................439
Adding Values to Multivalue Lookup Fields ...............................................442
Modifying a Record with DAO .....................................................................445
Modifying a Record with ADO .....................................................................448
Editing Multiple Records with ADO ............................................................449
Deleting a Record with DAO .........................................................................451
Deleting a Record with ADO.........................................................................453
Deleting Attachments .....................................................................................454
Copying Records to an Excel Worksheet .....................................................456
Copying Records to a Word Document .......................................................460
Copying Records to a Text File ......................................................................464
Filtering Records Using the SQL WHERE Clause ......................................467
Filtering Records Using the Filter Property .................................................496
Sorting Records ...............................................................................................471
Chapter Summary ...........................................................................................473

Chapter 16 Creating and Running Queries with DAO/ADO ........475


Creating a Select Query Manually ................................................................476
Creating a Select Query with DAO ...............................................................481
Creating a Select Query with ADO...............................................................483
Executing an Existing Select Query with ADO...........................................486
xvi C ONTENTS

Modifying an Existing Query with ADO .....................................................489


Creating and Running a Parameter Query with DAO ...............................491
Creating and Running a Parameter Query with ADO ...............................493
Creating and Running a Make-Table Query with DAO.............................497
Creating and Running an Update Query with DAO ..................................499
Executing an Update Query with ADO .......................................................501
Running an Append Query with DAO/ADO..............................................503
Running a Delete Query with DAO ..............................................................506
Creating and Running a Pass-Through Query with DAO .........................509
Creating and Executing a Pass-Through Query with ADO ......................511
Performing Other Operations with Queries ................................................515
Retrieving Query Properties with DAO ..................................................515
Listing All Queries in a Database with DAO/ADO ...............................517
Deleting a Query from a Database with DAO/ADO .............................519
Determining if a Query Is Updatable ......................................................520
Chapter Summary ...........................................................................................523

Chapter 17 Using Advanced ADO/DAO Features ..........................525


Fabricating a Recordset ..................................................................................526
Disconnected Recordsets ...............................................................................529
Saving a Recordset to Disk .............................................................................531
Cloning a Recordset ........................................................................................548
Introduction to Data Shaping ........................................................................553
Writing a Simple SHAPE Statement.........................................................555
Working with Data Shaping ......................................................................556
Writing a Complex SHAPE Statement.....................................................561
Shaped Recordsets with Multiple Children ........................................561
Shaped Recordsets with Grandchildren .............................................565
Transaction Processing ...................................................................................576
Creating a Transaction with ADO ...........................................................577
Creating a Transaction with DAO ............................................................579
Chapter Summary ...........................................................................................583

Chapter 18 Implementing Database Security .................................585


Two Types of Security in Microsoft Access..................................................586
Share-Level Security (in Access .accdb and .mdb
File Formats) ...........................................................................................586
CONTENTS xvii

User-Level Security.....................................................................................587
Understanding Workgroup Information Files ............................................587
Creating and Joining Workgroup Information Files..............................590
Opening a Secured MDB Database ..............................................................596
Creating and Managing Group and User Accounts....................................599
Deleting User and Group Accounts .........................................................603
Listing User and Group Accounts ............................................................605
Listing Users in Groups .............................................................................606
Setting and Retrieving User and Group Permissions .................................608
Determining the Object Owner................................................................608
Setting User Permissions for an Object ...................................................611
Setting User Permissions for a Database .................................................614
Setting User Permissions for Containers .................................................616
Checking Permissions for Objects............................................................618
Setting a Database Password Using the
CompactDatabase Method ...............................................................621
Setting a Database Password Using the
NewPassword Method.......................................................................622
Changing a User Password ........................................................................624
Encrypting a Secured MDB Database ..........................................................626
Chapter Summary ...........................................................................................628

PART 6—PROGRAMMING WITH THE JET DATA DEFINITION


LANGUAGE

Chapter 19 Creating, Modifying, and Deleting Tables


and Fields ......................................................................631
Creating Tables ................................................................................................634
Deleting Tables.................................................................................................639
Modifying Tables with DDL ..........................................................................640
Adding New Fields to a Table ...................................................................641
Changing the Data Type of a Table Column ...........................................642
Changing the Size of a Text Column........................................................643
Deleting a Column from a Table ..............................................................644
Adding a Primary Key to a Table..............................................................645
Adding a Multiple-Field Index to a Table................................................646
Deleting an Indexed Column ....................................................................647
Deleting an Index .......................................................................................648
xviii C ONTENTS

Setting a Default Value for a Table Column ............................................649


Changing the Seed and Increment Value of
AutoNumber Columns .....................................................................651
Chapter Summary ...........................................................................................653

Chapter 20 Enforcing Data Integrity and Relationships


between Tables ..............................................................655
Using CHECK Constraints ............................................................................656
Establishing Relationships between Tables ..................................................662
Using the Data Definition Query Window ..................................................666
Chapter Summary ...........................................................................................668

Chapter 21 Defining Indexes and Primary Keys ............................669


Creating Tables with Indexes .........................................................................670
Adding an Index to an Existing Table...........................................................671
Creating a Table with a Primary Key ............................................................673
Creating Indexes with Restrictions ...............................................................674
Deleting Indexes ..............................................................................................678
Chapter Summary ...........................................................................................679

Chapter 22 Database Security .........................................................681


Setting the Database Password ......................................................................682
Removing the Database Password.................................................................683
Creating a User Account.................................................................................685
Changing a User Password .............................................................................686
Creating a Group Account .............................................................................687
Adding Users to Groups .................................................................................689
Removing a User from a Group.....................................................................690
Deleting a User Account .................................................................................690
Granting Permissions for an Object..............................................................691
Revoking Security Permissions .....................................................................693
Deleting a Group Account .............................................................................694
Chapter Summary ...........................................................................................695

Chapter 23 Views and Stored Procedures .......................................697


Creating a View................................................................................................698
Enumerating Views .........................................................................................701
CONTENTS xix

Deleting a View ................................................................................................702


Creating a Stored Procedure ..........................................................................703
Creating a Parameterized Stored Procedure ................................................704
Examining the Contents of a Stored Procedure ..........................................707
Executing a Parameterized Stored Procedure..............................................708
Deleting a Stored Procedure ..........................................................................710
Changing Database Records with Stored Procedures ................................711
Chapter Summary ...........................................................................................711

PART 7—ENHANCING THE USER EXPERIENCE

Chapter 24 Enhancing Access Forms ..............................................715


Creating Access Forms ...................................................................................716
Grouping Controls Using Layouts ................................................................718
Rich Text Support in Forms ...........................................................................720
Using Built In Formatting Tools ....................................................................721
Using Images in Access Forms ......................................................................721
Using the Attachments Control .....................................................................723
Chapter Summary ...........................................................................................727

Chapter 25 Using Form Events........................................................729


Data Events .......................................................................................................730
Current .........................................................................................................731
BeforeInsert .................................................................................................732
AfterInsert ...................................................................................................733
BeforeUpdate...............................................................................................734
AfterUpdate .................................................................................................735
Dirty .............................................................................................................737
OnUndo .......................................................................................................738
Delete............................................................................................................738
BeforeDelConfirm ......................................................................................739
AfterDelConfirm ........................................................................................741
Focus Events .....................................................................................................742
Activate ........................................................................................................742
Deactivate ....................................................................................................742
GotFocus ......................................................................................................743
LostFocus .....................................................................................................743
xx C ONTENTS

Mouse Events ...................................................................................................743


Click..............................................................................................................743
DblClick .......................................................................................................745
MouseDown ................................................................................................745
MouseMove .................................................................................................746
MouseUp......................................................................................................747
MouseWheel................................................................................................747
Keyboard Events ..............................................................................................747
KeyDown .....................................................................................................747
KeyPress .......................................................................................................749
KeyUp ...........................................................................................................750
Error Events......................................................................................................752
Error .............................................................................................................752
Filter Events ......................................................................................................753
Filter .............................................................................................................753
ApplyFilter ...................................................................................................755
Timing Events ..................................................................................................757
Timer ............................................................................................................757
Events Recognized by Form Sections ...........................................................758
DblClick (Form Section Event) ................................................................758
Understanding and Using the OpenArgs Property ....................................759
Chapter Summary ...........................................................................................765

Chapter 26 Events Recognized by Form Controls ..........................767


Enter (Control) ................................................................................................768
BeforeUpdate (Control)..................................................................................770
AfterUpdate (Control) ....................................................................................771
NotInList (Control) .........................................................................................773
Click (Control).................................................................................................774
DblClick (Control) ..........................................................................................780
Chapter Summary ...........................................................................................782

Chapter 27 Enhancing Access Reports and Using


Report Events ...............................................................783
Creating Access Reports .................................................................................784
Using Report Events ........................................................................................784
Open .............................................................................................................784
Close .............................................................................................................786
CONTENTS xxi

Activate ........................................................................................................787
Deactivate ....................................................................................................788
NoData .........................................................................................................788
Page...............................................................................................................789
Error .............................................................................................................790
Events Recognized by Report Sections .........................................................792
Format (Report Section Event) .................................................................792
Print (Report Section Event) .....................................................................795
Retreat (Report Section Event) .................................................................799
Using the Report View ....................................................................................799
Sorting and Grouping Data ............................................................................801
Saving Reports in .pdf or .xps File Format...................................................802
Using the OpenArgs Property of the Report Object ..................................803
Chapter Summary ...........................................................................................806

Chapter 28 Advanced Event Programming ....................................807


Sinking Events in Standalone Class Modules ..............................................808
Writing Event Procedure Code in Two Places.............................................818
Responding to Control Events in a Class .....................................................818
Declaring and Raising Events ........................................................................822
Chapter Summary ...........................................................................................827

Chapter 29 Programming the User Interface .................................829


The Initial Microsoft Access 2013 Window .................................................830
The Quick Access Toolbar ..............................................................................830
Customizing the Navigation Pane .................................................................831
Using VBA to Customize the Navigation Pane ...........................................834
Locking the Navigation Pane ....................................................................835
Controlling the Display of Database Objects ..........................................835
Setting Displayed Categories .....................................................................837
Saving and Loading the Configuration of the Navigation Pane ...........837
A Quick Overview of the Access 2013 Ribbon Interface ...........................840
Ribbon Programming with XML, VBA, and Macros .................................843
Creating the Ribbon Customization XML Markup ...............................844
Loading Ribbon Customizations from an External
XML Document .................................................................................848
Embedding Ribbon XML Markup in a VBA Procedure .......................854
xxii C ONTENTS

Storing Ribbon Customization XML Markup in a Table ...................... 855


Assigning Ribbon Customizations to Forms and Reports .................... 860
Using Images in Ribbon Customizations ..................................................... 864
Requesting Images via the loadImage Callback ..................................... 864
Requesting Images via the getImage Callback ........................................ 868
Understanding Attributes and Callbacks ................................................ 873
Using Various Controls in Ribbon Customizations .................................... 874
Creating Toggle Buttons ............................................................................ 875
Creating Split Buttons, Menus, and Submenus....................................... 876
Creating Checkboxes.................................................................................. 878
Creating Edit Boxes .................................................................................... 879
Creating Combo Boxes and Drop Downs ............................................... 880
Creating a Dialog Box Launcher .............................................................. 882
Disabling a Control .................................................................................... 883
Repurposing a Built-in Control ................................................................ 884
Refreshing the Ribbon ............................................................................... 884
The CommandBars Object and the Ribbon................................................. 887
Tab Activation and Group Auto-Scaling ...................................................... 889
Customizing the Backstage View .................................................................. 891
Customizing the Quick Access Toolbar (QAT) ........................................... 896
Chapter Summary ........................................................................................... 897

PART 8—VBA AND MACROS

Chapter 30 Macros and Templates .................................................. 901


Macros or VBA? .............................................................................................. 902
Access 2013 Macro Security ........................................................................... 903
Using the AutoExec Macro ............................................................................ 905
Understanding Macro Actions, Arguments, and Program Flow ......... 906
Creating and Using Macros in Access 2013 ................................................. 909
Creating Standalone Macros ................................................................ 909
Running Standalone Macros ................................................................ 914
Creating and Using Submacros ............................................................ 915
Creating and Using Embedded Macros .............................................. 917
Copying Embedded Macros ................................................................. 918
Using Data Macros ................................................................................ 925
Creating a Data Macro .......................................................................... 926
CONTENTS xxiii

Creating a Named Data Macro ............................................................933


Editing an Existing Named Macro ......................................................935
Calling a Named Macro from Another Macro ..................................936
Using ReturnVars in Data Macros .......................................................936
Tracing Data Macro Execution Errors ................................................938
Error Handling in Macros ....................................................................941
Using Temporary Variables in Macros .........................................................943
Converting Macros to VBA Code .......................................................945
Converting Standalone Macros to VBA .............................................945
Converting Embedded Macros to VBA ..............................................946
Access Templates .............................................................................................948
Creating a Custom Blank Database Template.........................................948
Understanding the .accdt File Format .....................................................948
Chapter Summary ...........................................................................................953

PART 9—TAKING YOUR VBA PROGRAMMING


SKILLS TO THE WEB

Chapter 31 Access and Active Server Pages ....................................957


Introduction to Classic ASP ...........................................................................958
Creating an ASP Page .....................................................................................960
The ASP Object Model ...................................................................................966
Installing Internet Information Services (IIS) .............................................966
Creating a Virtual Directory ..........................................................................969
Setting ASP Configuration Properties ..........................................................971
Turning Off Friendly HTTP Error Messages ...............................................972
Running your First ASP Script ......................................................................974
Retrieving Records ..........................................................................................976
Breaking Up a Recordset When Retrieving Records .............................978
Retrieving Records with the GetRows Method ......................................986
Database Lookup Using Drop-Down Lists ..................................................990
Database Lookup Using a Multiple-Selection Listbox ...............................994
Adding Data to a Table ................................................................................ 1001
Modifying a Record...................................................................................... 1005
Deleting a Record ......................................................................................... 1011
Creating a Web User Interface for Database Access ................................ 1015
Chapter Summary ........................................................................................ 1020
xxiv C ONTENTS

Chapter 32 XML Features in Access 2013 .....................................1021


What Is XML? ............................................................................................... 1022
What Is a Well-Formed XML Document? ........................................... 1023
XML Support in Access 2013 ...................................................................... 1024
Exporting XML Data ................................................................................... 1024
Understanding the XML Data File ........................................................ 1027
Understanding the XML Schema File................................................... 1030
Understanding the XSL Transformation Files ..................................... 1032
Viewing XML Documents Formatted with Stylesheets...................... 1035
Advanced XML Export Options ............................................................ 1037
Data Export Options .......................................................................... 1037
Schema Export Options ..................................................................... 1039
Presentation Export Options............................................................. 1039
Applying XSLT Transforms to Exported Data.......................................... 1040
Importing XML Data ................................................................................... 1047
Programmatically Exporting to and Importing from XML ................... 1053
Exporting to XML Using the ExportXML Method ............................ 1053
Transforming XML Data with the TransformXML Method ............. 1062
Importing to XML Using the ImportXML Method ............................ 1070
Manipulating XML Documents Programmatically ................................. 1070
Loading and Retrieving the Contents of an XML File........................ 1072
Working with XML Document Nodes ................................................. 1073
Retrieving Information from Element Nodes...................................... 1075
Retrieving Specific Information from Element Nodes ....................... 1077
Retrieving the First Matching Node...................................................... 1078
Using ActiveX Data Objects with XML..................................................... 1079
Saving an ADO Recordset as XML to Disk.......................................... 1079
Attribute-Centric and Element-Centric XML ..................................... 1081
Changing the Type of an XML File ....................................................... 1082
Applying an XSL Stylesheet .................................................................... 1083
Transforming Attribute-Centric XML Data into
an HTML Table ................................................................................... 1085
Loading an XML Document in Excel ................................................... 1089
Chapter Summary ........................................................................................ 1091

Index ..............................................................................................1093
ACKNOWLEDGMENTS

F
irst, I’d like to express my gratitude to everyone at Mercury Learning and
Information. A sincere thank-you to my publisher, David Pallai, for offering
me the opportunity to update this book to the new 2013 version and tire-
lessly keeping things on track during this long project.
A whole bunch of thanks go to the editorial team for working so hard to bring this
book to print. In particular, I would like to thank the copyeditor, Tracey McCrea, for
the thorough review of my writing. To Jennifer Blaney, for her production expertise
and keeping track of all the edits and file processing issues. To the compositor,
L. Swaminathan at SwaRadha Typesetting, for all the typesetting efforts that gave
this book the right look and feel.
Special thanks to my husband, Paul, for his patience during this long project
and having to put up with frequent take out dinners.
Finally, I’d like to acknowledge readers like you who cared enough to post
reviews of the previous edition of this book online. Your invaluable feedback has
helped me raise the quality of this work by including the material that matters to
you most. Please continue to inspire me with your ideas and suggestions.

xxv
INTRODUCTION

F
or many years now, Microsoft Access has allowed users to design and de-
velop Windows-based database applications, and Access continues to be the
world’s most popular database. This book is for people who have already
mastered the use of Microsoft® Access® databases and now are ready for the next
step — programming. Microsoft Access 2013 Programming by Example with VBA,
XML, and ASP takes nonprogrammers through detailed steps of creating Access
databases from scratch and shows them how to retrieve and manage their data
programmatically using various programming languages and techniques. With this
book in hand, users can quickly build the toolset required for developing their own
database solutions. With this book’s approach, programming an Access database
from scratch and controlling it via programming code is as easy as designing and
maintaining databases with the built-in tools of Access. This book gives a practical
overview of many programming languages and techniques necessary in program-
ming, maintaining, and retrieving data from today’s Access databases.

PREREQUISITES

You don’t need any programming experience to use Microsoft Access 2013 Pro-
gramming by Example with VBA, XML, and ASP. The only prerequisite is that you
already know how to manually design an Access database and perform database
tasks by creating and running various types of queries. This book also assumes that
you know how to create more complex forms with embedded subforms, combo
boxes, and other built-in controls. If you don’t have these skills, there are countless
books on the market that can teach you step by step how to build simple databases.
If you do meet these criteria, this book will take you to the Access programming
level by example. You will gain working knowledge immediately by performing

xxvii
xxviii INTRODUCTION

concrete tasks and without having to read long descriptions of concepts. True
learning by example begins with the first step, followed by the next step, and the
next one, and so on. By the time you complete all of the steps in a hands-on exer-
cise or a custom project, you should be able to effectively apply the same technique
again and again in your own database projects.

HOW THIS BOOK IS ORGANIZED

This book is divided into nine parts (a total of 32 chapters) that progressively in-
troduce you to programming Access databases.
Part I introduces you to Access 2013 VBA programming. Visual Basic for Ap-
plications (VBA) is the programming language for Microsoft Access. In this part
of the book, you acquire the fundamentals of VBA that you will use over and over
again in building real-life Access database applications.

PART I CONSISTS OF THE FOLLOWING FOUR CHAPTERS:

Chapter 1 — Writing Procedures in Modules


In this chapter you learn about the types of Access procedures you can write and
learn how and where they are written.
Chapter 2 — Exploring the Visual Basic Editor (VBE)
In this chapter you learn almost everything you need to know about working
with the Visual Basic Editor window, commonly referred to as VBE. Some of
the programming tools that are not covered here are discussed and put to use in
Chapter 9.
Chapter 3 — Using Variables, Data Types, and Constants
This chapter introduces basic VBA concepts that allow you to store various pieces
of information for later use.
Chapter 4 — Passing Arguments to Procedures and Functions
In this chapter you find out how to provide additional information to your proce-
dures and functions before they are run.
While learning the fundamentals of VBA in Part I allows you to write simple
functions and procedures that do not require any complex logic, Part II of the book
teaches you how decisions and looping statements enable you to control program
flow and create more useful VBA procedures and functions.
INTRODUCTION xxix

PART II CONSISTS OF THE FOLLOWING TWO CHAPTERS:

Chapter 5 — Decision Making with VBA


In this chapter you learn how to control your program flow with a number of dif-
ferent decision-making statements.
Chapter 6 — Repeating Actions in VBA
In this chapter you learn how to repeat the same actions in your code by using
looping structures.
Although you can use individual variables to store data while your VBA code is
executing, many advanced VBA procedures will require that you implement more
efficient methods of keeping track of multiple values. In Part III, you’ll learn about
working with groups of variables (arrays) and storing data in collections.

AGAIN, THERE ARE TWO CHAPTERS IN PART III:

Chapter 7 — Working with Arrays


In this chapter you learn about static and dynamic arrays and how to use them for
holding various values.
Chapter 8 — Working with Collections and Class Modules
This chapter teaches you how you can create and use your own objects and col-
lections of objects.
While you may have planned to write a perfect VBA procedure, there is always
a chance that incorrectly constructed or typed code, or perhaps logic errors, will
cause your program to fail or produce unexpected results. In Part IV of this book,
you’ll learn about various methods of handling errors, testing, and debugging VBA
procedures.

PART IV ALSO CONTAINS TWO CHAPTERS:

Chapter 9 — VBE Tools for Testing and Debugging


In this chapter you begin using built-in debugging tools to test your programming
code.
Chapter 10 — Conditional Compilation and Error Trapping
This chapter introduces additional techniques that you will find useful for debug-
ging your Visual Basic applications. In particular, you will learn how conditional
compilation can help you to include or ignore certain blocks of code, and how you
can add effective error-handling code to your procedures.
xxx INTRODUCTION

The skills obtained in Parts I, II, III, and IV are fairly portable. They can be
utilized in programming other Microsoft Office applications that also use VBA as
their native programming language such as Excel, Word, PowerPoint, Outlook, and
so on.
Part V introduces you to two sets of programming objects known as Data Ac-
cess Objects (DAO) and ActiveX Data Objects (ADO) that enable Microsoft Access
and other client applications to access and manipulate data. In this part of the book,
you learn how to use DAO and ADO objects in your VBA code to connect to a data
source; create, modify, and secure database objects.

PART V CONSISTS OF THE FOLLOWING EIGHT CHAPTERS:

Chapter 11 — Data Access Technologies in Microsoft Access


In this chapter you get acquainted with two database engines (Jet/ACE) that Access
uses, as well as several object libraries that provide objects, properties, and methods
for your VBA procedures.
Chapter 12 — Creating and Accessing Database Tables and Fields
This chapter demonstrates how to create, copy, link, and delete database tables pro-
grammatically by using objects from the DAO and ADO object libraries. You also
learn how to write code to add and delete fields as well as create listings of existing
tables in a database and fields in a table.
Chapter 13 — Setting Up Primary Keys, Indexes, and Table Relationships
In this chapter you learn how to write VBA code to add primary keys and indexes
to your database tables using objects, properties, and methods from the DAO and
ADO object libraries. You also learn how to use objects from the ADOX library to
create relationships between your tables.
Chapter 14 — Finding and Reading Records
Here you practice various methods of using programming code to open a set of da-
tabase records, commonly referred to as a recordset. You learn how to move around
in a recordset, and find, filter, and sort the required records, as well as read their
contents. This chapter covers both DAO and ADO recordsets.
Chapter 15 — Working with Records
This chapter teaches you essential database operations such as adding, updating,
and deleting records. You also learn how to render your database records in three
popular formats (Excel, Word, and a text file).
INTRODUCTION xxxi

Chapter 16 — Creating and Running Queries with DAO/ADO


In this chapter you learn how to use VBA code instead of the Query Design view to
create and run various types of database queries.
Chapter 17 — Using Advanced ADO/DAO Features
This chapter explains several advanced ADO/DAO features such as how to discon-
nect a recordset from a database, save it in a disk file, clone it, and shape it. You also
learn about database transactions.
Chapter 18 — Implementing Database Security
In this chapter you learn about two types of security in Microsoft Access databases:
share-level security that applies to both older (MDB) and new (ACCDB) Access
databases, and user-level security that can only be used with .mdb files.
You will find the skills obtained in Part V of this book essential for accessing,
manipulating, and securing Access databases.
Part VI introduces you to the Data Definition Language (DDL), an important
component of the Structured Query Language (SQL). Like ADO and DAO, which
were introduced in Part V, DDL is used for defining database objects (tables, views,
stored procedures, primary keys, indexes, and constraints) and managing database
security. In this part of the book, you learn how to use DDL statements with Jet/
ACE databases, ADO, and the Jet OLE DB Provider.

PART VI CONSISTS OF THE FOLLOWING FIVE CHAPTERS:

Chapter 19 — Creating, Modifying, and Deleting Tables and Fields


In this chapter you learn special Data Definition Language commands for creating
a new Access database, as well as creating, modifying, and deleting tables. You also
learn commands for adding, modifying, and deleting fields and indexes.
Chapter 20 — Enforcing Data Integrity and Relationships between Tables
Here you learn how to define rules regarding the values allowed in table fields to
enforce data integrity and relationships between tables.
Chapter 21 — Defining Indexes and Primary Keys
Here you learn DDL commands for creating indexes and primary keys.
Chapter 22 — Database Security
In this chapter you learn how to use DDL commands to manage security in the
Microsoft Access database. You learn how to quickly create, modify, and remove a
database password, and how to manage user-level accounts.
xxxii INTRODUCTION

Chapter 23 — Views and Stored Procedures


This chapter shows you how to work with two powerful database objects known as
views and stored procedures. You learn how views are similar to SELECT queries,
and how stored procedures can perform various actions similar to Access Action
queries and Select queries with parameters.
The skills you learn in Part VI of this book will allow you to create, manipulate,
and secure your Access databases using SQL DDL statements. Numerous Access
SQL DDL statements and concepts introduced here are important in laying the
groundwork for moving into the client/server environment (porting your Micro-
soft Access database to SQL Server).
Part VII introduces you to responding to events that occur in Access forms and
reports. The behavior of Microsoft Access objects such as forms, reports, and con-
trols can be modified by writing programming code known as an event procedure
or an event handler. In this part of the book, you learn how you can make your
forms, reports, and controls perform useful actions by writing event procedures in
class modules. You also learn how to use VBA, macros, and XML to customize the
user interface in Access 2013.

PART VII CONSISTS OF THE FOLLOWING SIX CHAPTERS:

Chapter 24 — Enhancing Access Forms


This chapter presents a quick overview of types of forms you can create with Access
2013 and types of formatting you can apply to make your forms more attractive.
You learn how you can group form controls using the layouts, implement rich for-
matting in form controls, professionally format your forms using built-in themes,
and enhance forms with images.
Chapter 25 — Using Form Events
In this chapter you learn the types of events that can occur on a Microsoft Access
form and write event procedures to handle various form events.
Chapter 26 — Events Recognized by Form Controls
In this chapter you work with a custom application and learn how to write event
procedures for various controls that are placed on an Access form.
Chapter 27 — Enhancing Access Reports and Using Report Events
In this chapter you learn about many events that are triggered when an Access re-
port is run. You write your own event procedures to specify what happens when the
report is opened, activated/deactivated, or closed.
INTRODUCTION xxxiii

Chapter 28 — Advanced Event Programming


This chapter teaches advanced concepts in event programming. You learn how to
respond to events in standalone class modules to make your code more manage-
able and portable to other objects. You also learn how to create and raise your own
events.
Chapter 29—Programming the User Interface
This chapter provides an overview of the programming elements available in the
Ribbon and shows how you can customize the user interface (UI) in your Access
database applications. You learn how to create XML Ribbon customization markup
and load it in your database. You also learn how Ribbon customizations can be as-
signed to forms or reports.
The skills acquired in Part VII of this book will allow you to enhance and alter
the way users interact with your database application.
Writing VBA code is not the only way to provide rich functionality to your Ac-
cess database users. Macros have long been used to enhance the user experience
without users having to write any VBA code. Access 2013 Macro Designer allows
you to include complex logic, business rules, and error handling in your macros.
In Part VIII of this book, you are introduced to three types of macros that you can
create in Access 2013. In addition, you learn how to convert macros to VBA and get
started with built-in templates that extensively use macros.

PART VIII CONTAINS THE FOLLOWING CHAPTER:

Chapter 30 —Macros and Templates


This chapter introduces you to the new features in Access 2013 macros. We take a
detailed look at macro security, work with three types of macros (standalone, em-
bedded, and data macros), see examples of using variables in macros, and examine
error-handling actions in macros. We also discuss working with the template for-
mat in Access 2013.
The skills acquired in Part VIII will allow you to utilize macros in your Access
forms and reports, as well as in automating Access Web Applications that are not
compatible with VBA.
Part IX introduces you to programming Microsoft Access databases for Internet
access. Gone are the times when working with Access required the presence of the
Microsoft Access application on a user’s desktop. Thanks to the development of
Internet technologies, you can publish both static and dynamic Access data to the
Web. In this part of the book, you learn how Active Server Pages (ASP) and Exten-
sible Markup Language (XML) are used with Access to develop database solutions
for the World Wide Web.
xxxiv INTRODUCTION

PART IX CONSISTS OF THE FOLLOWING TWO CHAPTERS:

Chapter 31 — Access and Active Server Pages


In this chapter you learn how to use Microsoft’s Active Server Pages (ASP) technol-
ogy to view, insert, delete, and modify records stored in a Microsoft Access data-
base from a Web browser.
Chapter 32 — XML Features in Access 2013
In this chapter you learn how to use the Extensible Markup Language (XML) with
Access. You learn how to manually and programmatically export Access data to
XML files, as well as import an XML file to Access and display its data in a table.
You also learn how to use style sheets and transformations to present Access data
to users in a desired format.
The skills acquired in Part IX of this book will make your Access applications
Internet and intranet ready. You are now able to connect to, read from, and write
to Access databases from within a Web browser using two important Microsoft
technologies.

HOW TO WORK WITH THIS BOOK

This book has been designed as a tutorial and should be followed chapter by chapter.
As you read each chapter, perform the tasks that are described. Be an active
learner by getting involved in the book’s hands-on exercises and custom projects.
When you are completely involved, you learn things by doing rather than studying,
and you learn faster. Do not move on to new information until you’ve fully grasped
the current topic. Allow your brain to sort things out and put them in proper per-
spective before you move on. Take frequent breaks between your learning sessions,
as some chapters in this book cover lots of material. Do not try to do everything in
one sitting. It’s always better to divide the material into smaller units than attempt
to master all there is to learn at once. However, never stop in the middle of a hands-
on exercise; finish it before taking a break. After learning a particular technique or
command, try to think of ways to apply it to your own work. As you work with this
book, create small sample procedures for yourself based on what you’ve learned
up to a particular point. These procedures will come in handy when you need to
review the subject in the future or simply need to steal some ready-made code.

THE COMPANION FILES

The example files for all the hands-on activities in this book are available on the
CD-ROM disc included with this book.
INTRODUCTION TO
P a rt 1 ACCESS 2013 VBA
PROGRAMMING

Chapter 1 Writing Procedures in Modules


Chapter 2 Exploring the Visual Basic Editor (VBE)
Chapter 3 Using Variables, Data Types, and Constants
Chapter 4 Passing Arguments to Procedures and Functions

V
isual Basic® for Applications (VBA) is the programming language for
Microsoft® Access®. In this part of the book, you acquire the fundamen-
tals of VBA that you will use over and over again in building real-life
Microsoft Access database applications.

1
WRITING
Ch ap t er 1 PROCEDURES IN
MODULES

T
his chapter’s objective is to introduce you to writing programming code
using the built-in language of Microsoft Access—Visual Basic for Appli-
cations (commonly referred to as VBA). By writing your own code you
can extend the functionality of existing Microsoft Access database applications
or create your own applications from scratch. VBA is a language embedded in
all the Microsoft Office applications. Therefore, what you learn in this book
about Access programming can be utilized in writing programs that control
Excel®, Word®, Outlook®, or Project. Your job as a programmer (at least dur-
ing the course of this book) will boil down to writing various procedures. A
procedure is a group of instructions that allows you to accomplish specific tasks
when your program runs. When you place instructions (programming code)
in a procedure, you can call this procedure whenever you need to perform that
particular task. Although many tasks can be automated in Access 2013 by using
macro actions, such as opening forms and reports, finding records, and execut-
ing queries, you will need VBA skills to perform advanced customizations in
your desktop databases.

3
4 M ICROSOFT A CCESS 2013 PROGRAMMING

PROCEDURE TYPES
VBA has the following types of procedures: subroutine procedures, function
procedures, event procedures, and property procedures. You create and store
procedures in modules. Each procedure in the same module must have a unique
name; however, procedures in different modules can have the same name. Let’s
learn a bit about each procedure type so that you can quickly recognize them
when you see them in books, magazine articles, or online.
1. Subroutine procedures (also called subroutines or subprocedures)
Subroutine procedures perform useful tasks but never return values. They be-
gin with the keyword Sub and end with the keywords End Sub. Keywords are
words that carry a special meaning in VBA. Let’s look at the simple subroutine
ShowMessage that displays a message to the user:
Sub ShowMessage()
MsgBox "This is a message box in VBA."
End Sub

Notice a pair of empty parentheses after the procedure name. The instruction
that the procedure needs to execute is placed on a separate line between the Sub
and End Sub keywords. You may place one or more instructions and even com-
plex control structures within a subroutine procedure. Instructions are also
called statements. The ShowMessage procedure will always display the same
message when executed. MsgBox is a built-in VBA function often used for pro-
gramming user interactions (see Chapter 4, "Passing Arguments to Procedures
and Functions," for more information on this function). To execute the preced-
ing subroutine programmatically, you need to write the following line of code:
Call ShowMessage()

The Call statement followed by the procedure name tells VBA to execute the
instructions contained within the named procedure. If you’d like to write a
more universal procedure that can display a different message each time the
procedure is executed, you will need to write a subroutine that takes argu-
ments. Arguments are values that are needed for a procedure to do something.
Arguments are placed within the parentheses after the procedure name. Let’s
look at the following procedure that also displays a message to the user; how-
ever, this time we can pass any text string to display:
Sub ShowMessage2(strMessage)
MsgBox strMessage
End Sub
WRITING PROCEDURES IN M ODULES 5

This subprocedure requires one text value before it can be run; strMessage is
the arbitrary argument name. It can represent any text you want. Therefore, if
you pass it the text "Today is Monday," that is the text the user will see when the
procedure is executed. If you don’t pass the value to this procedure, VBA will
display an error.
If your subprocedure requires more than one argument, list the arguments
within the parentheses and separate them with commas. For example, let’s im-
prove the preceding procedure by passing it also a text string containing a user
name:
Sub ShowMessage3(strMessage, strUserName)
MsgBox strUserName & ", your message is: " & strMessage
End Sub

The ampersand (&) operator is used for concatenating text strings inside the
VBA procedure. If we pass to the above subroutine the text "Keep on learning."
as the strMessage argument and "John" as the strUserName argument, the pro-
cedure will display the following text in a message box:
John, your message is: Keep on learning.

To call this subroutine from another procedure, you can write the following
line of code:
Call ShowMessage3("Keep on learning.", "John")

Notice that when calling a procedure with arguments, the arguments are en-
closed in parentheses. The arguments are listed in the same order in which they
are specified in the procedure definition. See exceptions to this rule and dis-
cover more information about passing arguments to subprocedures and func-
tions in Chapter 4.
2. Function procedures (functions)
Functions perform specific tasks and can return values. They begin with the
keyword Function and end with the keywords End Function. Let’s look at a
simple function that adds two numbers:
Function addTwoNumbers()
Dim num1 As Integer
Dim num2 As Integer

num1 = 3
num2 = 2
addTwoNumbers = num1 + num2
End Function
6 M ICROSOFT A CCESS 2013 PROGRAMMING

The preceding function procedure always returns the same result, which is the
value 5. The Dim statements inside this function procedure are used to declare
variables that the function will use. A variable is a name that is used to refer
to an item of data. Because we want the function to perform a calculation, we
specify that the variables will hold integer values. Variables and data types used
in Access 2013 are covered in detail in Chapter 3, "Using Variables, Data Types,
and Constants."
The variable definitions (the lines with the Dim statements) are followed
by the variable assignment statements in which we assign specific numbers to
the variables num1 and num2. Finally, the calculation is performed by adding
together the values held in both variables: num1 + num2. To return the result
of our calculation, we set the function name to the value or the expression we
want to return:
addTwoNumbers = num1 + num2

Although this function example returns a value, not all functions have to return
values. Functions, like subroutines, can perform a number of actions without
returning any values.
Similar to procedures, functions can accept arguments. For example, to make
our addTwoNumbers function more versatile, we can rewrite it as follows:
Function addTwoNumbers2(num1 As Integer, num2 As Integer)
addTwoNumbers2 = num1 + num2
End Function

Now we can pass any two numbers to the preceding function to add them to-
gether. For example, we can write the following statement to display the result
of the function in a message box:
MsgBox("Total=" & addTwoNumbers2(34,80))

You will learn more about writing and calling functions in Chapter 4.
3. Event procedures
Event procedures are automatically executed in response to an event initiated
by the user or program code, or triggered by the system. Events, event proper-
ties, and event procedures are introduced later in this chapter. They are also
covered in Part IV, "Error Handling and Debugging."
4. Property procedures
Property procedures are used to get or set the values of custom properties
for forms, reports, and class modules. The three types of property proce-
dures (Property Get, Property Let, and Property Set) begin with the Property
WRITING PROCEDURES IN M ODULES 7

keyword followed by the property type (Get, Let, or Set), the property name,
and a pair of empty parentheses, and end with the End Property keywords.
Here’s an example of a property procedure that retrieves the value of an author’s
royalty:
Property Get Royalty()
Royalty = (Sales * Percent) – Advance
End Property

Property procedures are covered in detail in Chapter 8, "Working with Collec-


tions and Class Modules."

MODULE TYPES
As mentioned earlier, procedures are created and stored in modules. Like the
previous version, Access 2013 has two types of modules: standard and class.

Standard Modules
Standard modules are used to hold subprocedures and function procedures that
can be run from anywhere in the application because they are not associated
with any particular form or report.

Writing Procedures in a Standard Module


Because we already have a couple of procedures to try out, let’s do a quick
hands-on exercise to learn how to open standard modules, write procedures,
and execute them.

Please note files for the "Hands-On" project may be found on the companion
CD-ROM.

Hands-On 1.1. Working in a Standard Module


1. Create a folder on your hard drive named C:\Access2013_ByExample.
2. Open Access 2013 and click Blank Database (see Figure 1.1).TypeChap01 in-
the File Name box, and click the folder button to set the location for the data-
base to the C:\Access2013_ByExample folder. Finally, click the Create button
to create the specified database. Access will create the database in its default
.ACCDB format.
8 M ICROSOFT A CCESS 2013 PROGRAMMING

FIGURE 1.1. Creating a blank desktop Access 2013 database.

3. To launch the programming environment in Access 2013, select the Database


Tools tab and click Visual Basic (see Figure 1.2). You can also press Alt+F11
to get to this screen.

FIGURE 1.2. Switching to a Visual Basic development environment.

4. Insert a standard module by choosing Module from the Insert menu (see
Figure 1.3).

FIGURE 1.3. Inserting a standard module.


WRITING PROCEDURES IN M ODULES 9

FIGURE 1.4. Standard module.

Each module begins with a declaration section that lists various settings and
declarations that apply to every procedure in the module. Figure 1.4 shows the
default declaration. Option Compare specifies how string comparisons are eval-
uated in the module—whether the comparison is case sensitive or insensitive.
This is a case-insensitive comparison that respects the sort order of the data-
base. This means that "a" is the same as "A." If you delete the Option Compare
Database statement, the default string comparison setting for the module is
Option Compare Binary (used for case-sensitive comparisons where "a" is not
the same as "A").
Another declaration (not shown here), the Option Explicit statement is of-
ten used to ensure that all variable used within this module are formally de-
clared. You will learn more about this statement and variables in Chapter 4.
Following the declaration section is the procedure section, which holds the
module’s procedures. You can begin writing your procedures at the cursor po-
sition within the Module1 (Code) window.
5. In the Module1 (Code) window, enter the code of subroutines and function
procedures as shown in Figure 1.5.
Notice that Access inserts a horizontal line after each End Sub or End Function
keyword to make it easier to identify each procedure. The Procedure drop-
down box at the top-right corner of the Module1(Code) window displays the
name of the procedure in which the insertion point is currently located.
10 M ICROSOFT A CCESS 2013 PROGRAMMING

FIGURE 1.5. Standard module with subprocedures and functions.

Executing Your Procedures and Functions


Now that you’ve filled the standard module with some procedures and func-
tions, let’s see how you can run them. There are many ways of running your
code. In the next hands-on exercise, you will learn to run your code in four dif-
ferent ways, from the:
● Run menu (Run Sub/UserForm)
● Toolbar button (Run Sub/UserForm)
● Keyboard (F5)
● Immediate window

Hands-On 1.2. Running Procedures and Functions


1. Place the insertion point anywhere within the ShowMessage procedure. The
Procedure box in the top-right corner of the Module1 (Code) window should
display ShowMessage. Choose Run Sub/UserForm from the Run menu.
Access runs the selected procedure and displays the message box with the text
"This is a message box in VBA."
2. Click OK to close the message box. Try running this procedure again, this time
by pressing the F5 key on the keyboard. Click OK to close the message box. If
WRITING PROCEDURES IN M ODULES 11

the Access window seems stuck and you can’t activate any menu option, this is
often an indication that there is a message box open in the background. Access
will not permit you to do any operation until you close the pop-up window.
3. Now, run this procedure for the third time by clicking the Run Sub/UserForm
button ( ) on the toolbar. This button has the same tool tip as the Run Sub/
UserForm (F5) option on the Run menu.
Procedures that require arguments cannot be executed directly using
the methods you just learned. You need to type some input values
for these procedures to run. A perfect place to do this is the Immedi-
ate window, which is covered in detail in Chapter 2, "Exploring the
Visual Basic Editor (VBE)." For now, let’s open this window and see
how you can use it to run VBA procedures.
4. Select Immediate Window from the View menu.
Access opens a small window and places it just below the Module1 (Code)
window. You can size and reposition this window as needed. Figure 1.6 shows
statements that you will run from the Immediate window in Steps 5–8.
5. Type the following in the Immediate window and press Enter to execute.
ShowMessage2 "I’m learning VBA."

Access executes the procedure and displays the message in a message box. Click
OK to close the message box. Notice that to execute the ShowMessage2 pro-
cedure, you need to type the procedure name, a space, and the text you want
to display. The text string must be surrounded by double quotation marks.
In a similar way you can execute the ShowMessage3 procedure by providing
two required text strings. For example, on a new line in the Immediate window,
type the following statement and press Enter to execute:
ShowMessage3 "Keep on learning.", "John"

When you press the Enter key, Access executes the ShowMessage3 procedure
and displays the text "John, your message is: Keep on learning." Click OK to
close this message box.
You can also use the Call statement to run a procedure in the Imme-
diate window. When using this statement you must place the values
of arguments within parentheses, as shown here:
Call ShowMessage3("Keep on learning.", "John")

Function procedures are executed using different methods. Step 6 demon-


strates how to call the add Two Numbers function.
Another Random Scribd Document
with Unrelated Content
caractérisé par la sujétion individuelle, mais dans un état de profond
assujétissement collectif, qui constitue, à vrai dire, une condition
encore plus dégradante et moins favorable à un affranchissement
ultérieur.
On doit, à mon gré, regarder comme une loi générale de
dynamique sociale la tendance inévitable de toute civilisation
indigène, dans son développement spontané, vers un tel régime
initial, dont les traces se retrouvent partout, même au sein des
sociétés les plus avancées, et qui domine encore essentiellement
chez la majeure partie de la population asiatique, au point de
sembler aujourd'hui particulièrement propre à la race jaune, quoique
la race blanche n'en ait certes pas été d'abord plus exempte, et s'en
soit seulement plus rapidement et plus pleinement dégagée, ou en
vertu de sa supériorité effective, ou par suite de circonstances plus
favorables. Mais ce régime, que l'essor prépondérant de l'activité
militaire devait radicalement altérer, n'a pu devenir profondément
caractéristique que sous l'influence permanente, suffisamment
prononcée, des conditions extérieures qui pouvaient à la fois
entraver le plus l'élan de l'esprit guerrier et le mieux favoriser celui
de l'esprit sacerdotal. Ces causes locales, qui n'ont jamais pu exercer
ensuite une action sociale aussi capitale, ont surtout consisté dans la
réunion d'un heureux climat avec un sol fécond, qui devait faciliter le
développement intellectuel, en assurant aisément les subsistances,
pourvu d'ailleurs que la population, convenablement étendue,
occupât un territoire propre à établir spontanément des
communications intérieures, et enfin que le pays fût néanmoins, par
sa nature, assez pleinement isolé pour être préservé des
envahissemens extérieurs sans pousser fortement à la vie guerrière:
rien ne peut mieux satisfaire à cet ensemble d'indications que la
vallée d'un grand fleuve, séparée d'un côté par la mer, et, d'un
autre, par d'immenses déserts ou des montagnes inaccessibles.
Aussi ce grand système théocratique des castes s'est-il jadis
pleinement réalisé en Égypte, dans la Chaldée, dans la Perse, etc.; il
s'est prolongé jusqu'à nos jours dans la partie de l'Orient la moins
exposée au contact graduel de la race blanche, à la Chine, au Japon,
au Thibet, dans l'Indostan, etc.: par suite d'influences analogues, on
l'a de même essentiellement retrouvé au Mexique et au Pérou, à
l'époque de la conquête, sans qu'une telle similitude puisse, du
reste, y motiver aucune induction raisonnable sur des
communications peu compatibles avec l'esprit de ce régime. Outre
cette multiplicité d'exemples décisifs, qui suffirait à constater
directement la spontanéité fondamentale d'une semblable
organisation, on en peut signaler des traces plus ou moins
caractéristiques dans tous les cas de civilisation indigène; comme,
par exemple, pour notre Europe occidentale, chez les Gaulois et chez
les Étrusques. Parmi les nations dont le développement propre a été
surtout hâté par d'heureuses colonisations, on en reconnaît encore
l'influence primordiale; l'empreinte générale s'en fait toujours sentir
dans les diverses institutions ultérieures, et n'est pas même
aujourd'hui complétement effacée, au sein des sociétés les plus
avancées. En un mot, ce régime constitue partout le fond nécessaire
de l'ancienne civilisation.
Cette universalité plus ou moins prononcée et la profonde
ténacité qui caractérisent un tel système, doivent faire penser, quels
qu'en puissent être les vrais inconvéniens, qu'il était, aux temps de
sa splendeur, en harmonie intime avec les besoins essentiels de
l'humanité. Il est facile, en effet, de reconnaître qu'il a été
primitivement indispensable pour ébaucher, à tous égards, l'évolution
fondamentale, intellectuelle ou sociale. D'abord, sa spontanéité est
évidemment irrécusable; car rien n'est certes plus naturel, à
l'origine, que l'hérédité générale des professions, qui fournit aussitôt,
par la simple imitation domestique, le plus facile et le plus puissant
moyen d'éducation, le seul même alors praticable, tant que la
tradition orale doit constituer encore le principal mode de
transmission universelle, soit à défaut d'aucun autre procédé
suffisant, soit surtout en vertu du peu de rationnalité des
conceptions quelconques. A quelque perfectionnement même que
puisse jamais parvenir la civilisation humaine, il est clair que cette
tendance primitive à l'hérédité s'y fera inévitablement toujours sentir,
quoiqu'à un degré constamment décroissant, puisque la plupart des
hommes n'ayant point, à vrai dire, de vocations spéciales très
prononcées, chacun doit ordinairement se sentir disposé à
embrasser volontiers la profession paternelle, pour peu que la
société se trouve normalement classée; ce qui d'ailleurs n'empêche
point, aux époques de transition, l'ardeur momentanée mais
unanime à un déclassement général, alors plus ou moins nécessaire.
Malgré que cette hérédité volontaire, ou seulement imposée par les
mœurs, doive heureusement avoir, chez les modernes, un tout autre
caractère que l'hérédité forcée, tyranniquement prescrite aux
anciens par les lois, suivant l'esprit de toute leur économie sociale,
elle n'en procède pas moins, au fond, du même principe
élémentaire, d'après les garanties profondes que doit toujours offrir
au bonheur, soit privé, soit public, la plus complète préparation
possible de chacun à sa vraie destination sociale. Le seul moyen de
diminuer, sans aucun danger réel, individuel ou social, la nécessité
de ce mode spontané, consiste à rationnaliser de plus en plus
l'éducation humaine, en faisant passer, autant que le comporte
l'évolution intellectuelle, dans l'enseignement public, abstrait et
systématique, ce qui auparavant exigeait un apprentissage
domestique, concret et empirique. C'est ainsi surtout que le
catholicisme a fait irrévocablement cesser l'hérédité des fonctions
sacerdotales, aussi universelle, dans toute l'antiquité, que celle des
autres attributions quelconques, privées ou publiques.
En second lieu, les propriétés fondamentales de ce régime initial
ne sont pas moins incontestables, à tous égards, que son évidente
spontanéité. L'évolution intellectuelle lui devra toujours la première
division permanente entre la théorie et la pratique, alors
suffisamment ébauchée par le développement spécial d'une caste
spéculative, naturellement investie, même à un degré exorbitant, de
la dignité et du loisir indispensables à la plénitude et à la continuité
de ses travaux. Aussi, en tous genres, les élémens primitifs de nos
connaissances réelles remontent-ils nécessairement jusqu'à cette
grande époque, où l'esprit humain a enfin commencé à régulariser
sa marche générale. La même observation doit s'étendre aux beaux-
arts, alors soigneusement cultivés, indépendamment de leur charme
direct, par la caste dirigeante, soit comme accessoire du dogme et
du culte, soit comme moyen d'enseignement et de propagation.
Néanmoins c'est surtout le développement industriel qui, n'exigeant
pas d'aussi rares vocations intellectuelles, et ne pouvant inspirer
aucune inquiétude politique à la classe prépondérante, a dû être plus
spécialement secondé par un tel régime, sous lequel d'ailleurs l'état
de paix habituelle permettait d'employer les masses inférieures à des
opérations vraiment colossales, où la force supplée presque toujours
au génie, mais qui n'en eurent pas moins alors une véritable
importance. On ne saurait douter que tous les arts usuels ne doivent
y chercher leur premier essor, long-temps supérieur au grossier élan
des sociétés essentiellement militaires. La perte nécessairement
fréquente de diverses inventions utiles avant que cette organisation
conservatrice pût être convenablement établie, avait dû, sans doute,
en faire d'abord ressortir le besoin fondamental, et devait ensuite
faire habituellement apprécier ce puissant moyen de consolider le
degré de division du travail où notre espèce était déjà parvenue.
Jamais, à aucune autre époque, l'aptitude fondamentale du
polythéisme à fournir, par sa nature, des moyens généraux d'honorer
les divers talens, n'a été plus pleinement réalisée que sous cette
première organisation, qui a si souvent poussé jusqu'à l'apothéose
proprement dite la glorieuse commémoration des principaux
inventeurs, ainsi proposés à l'adoration habituelle des castes
respectives. Sous le point de vue social, la convenance primordiale
d'un tel régime n'est pas moins prononcée. Dans l'ordre politique
proprement dit, la stabilité constitue évidemment son principal
attribut. Toutes les précautions capitales s'y trouvaient
spontanément instituées, avec la plus grande énergie possible, pour
le préserver de toute grave atteinte, intérieure ou extérieure. Au
dedans, les diverses castes partielles, essentiellement isolées entre
elles, n'étaient habituellement liées que par leur commune
subordination à la caste sacerdotale, dont chacune d'elles devait
sans cesse éprouver le besoin fondamental, puisqu'elle y trouvait
exclusivement les lumières spéciales et l'impulsion propre qui lui
étaient journellement indispensables à tous égards. Jamais il n'a pu
exister ensuite une aussi intense concentration, régulière et
permanente, des pouvoirs humains, que celle alors naturellement
établie chez cette caste suprême, dont chaque membre, du moins
dans les rangs supérieurs de la hiérarchie pontificale, était à la fois,
non-seulement prêtre et magistrat, mais aussi savant, artiste,
ingénieur et médecin. Les hommes d'état de la Grèce et de Rome,
dont la plénitude et la généralité étaient si supérieures à ce qu'a pu
comporter jusqu'ici l'état moderne, paraissent, à leur tour, des
personnages fort incomplets, comparativement à ces admirables
natures théocratiques de la première antiquité, dont Moïse constitue
pour nous le type, sinon le plus fidèle, du moins le mieux connu.
Relativement à l'extérieur, ce régime ne pouvait courir
immédiatement de graves dangers que par le développement
toujours imminent de l'activité militaire, dont la politique sacerdotale
prévenait, autant que possible, les suites plus ou moins
perturbatrices, en ouvrant, de temps à autre, une issue convenable
à l'inquiétude des guerriers, par de larges expéditions lointaines et
par des colonisations irrévocables. Enfin, sous l'aspect purement
moral, on ne peut méconnaître la tendance nécessaire de ce régime
à développer soigneusement, par une première culture, à la fois
spontanée et systématique, la morale personnelle en ce qu'elle offre
de plus fondamental, mais surtout la morale domestique, trop
négligée ensuite par le polythéisme militaire, comme je l'ai expliqué
ci-dessus, et qui, dans ces théocraties, devait naturellement devenir
prépondérante, l'esprit de caste n'étant qu'une extension directe de
l'esprit de famille, et l'éducation y reposant toujours sur le principe
d'imitation. Quoique la polygamie y fût encore essentiellement
prépondérante, sauf quelques cas exceptionnels de monogamie fort
imparfaite et très précaire, la condition sociale des femmes recevait
pourtant alors sa première amélioration fondamentale, depuis l'âge
de barbarie où le sexe le plus faible restait communément assujéti
aux travaux pénibles dédaignés par le sexe prépondérant: leur
réclusion habituelle, suite d'ailleurs inévitable de la polygamie,
constituait déjà, en réalité, un premier hommage général, et un
témoignage involontaire de considération, tendant dès lors à leur
attribuer, dans l'ordre élémentaire de la société, une position de plus
en plus conforme à leur vraie nature caractéristique. Quant à la
morale sociale, il est évident que l'esprit de ce régime devait
directement développer, au plus haut degré, le respect des vieillards,
et le culte général des ancêtres. Le grand sentiment du patriotisme
n'y était encore, chez les masses, sauf l'attachement instinctif au sol
natal, qu'à son ébauche la plus élémentaire, l'amour de la caste, qui,
quelque étroit qu'il doive nous paraître, constitue un intermédiaire
indispensable dans l'essor graduel de la moralité humaine, surtout à
cette époque, et peut-être toujours sous de nouvelles formes. Du
reste, la profonde aversion superstitieuse qu'un tel système devait
inspirer pour toute relation avec l'étranger, et qui contribuait
beaucoup à augmenter son immuable consistance, doit être
soigneusement distinguée de l'actif dédain ultérieurement entretenu
par le polythéisme militaire.
Malgré tant d'éminentes propriétés, il est néanmoins certain que
ce grand système théocratique, après avoir ébauché, sous tous les
rapports, l'évolution humaine, devait devenir ensuite radicalement
antipathique aux principaux progrès ultérieurs, intellectuels ou
sociaux, en vertu même de l'excessive stabilité qui le caractérisait, et
qui tendait graduellement à se convertir en une immobilité opiniâtre,
quand les nouveaux développemens ont fini par exiger un autre
classement social[14]. Ce n'est pas que cette immuabilité soit, comme
on le pense, absolue: puisque ce régime n'est point, à beaucoup
près, identique au Thibet à ce qu'il est dans l'Inde, ni là surtout à ce
qu'il est devenu à la Chine, où l'introduction des examens graduels a
tant modifié l'institution des castes, sans toutefois la détruire
réellement; ce qui prouve clairement qu'un tel système n'est pas
immodifiable. Mais, quoique l'humanité dût sans doute
spontanément parvenir à s'y ouvrir enfin une issue quelconque,
cependant notre développement européen a heureusement dépendu
d'une toute autre marche, infiniment plus rapide, comme nous le
reconnaîtrons ci-après: en sorte qu'il est oiseux d'insister davantage
sur l'essor hypothétique compatible avec la seule théocratie, le
premier grand progrès général ayant dû précisément consister à
passer à une autre organisation, dans les pays où celle-là n'avait pu
s'enraciner suffisamment. On conçoit aisément, en effet, combien ce
régime purement conservateur doit bientôt prendre un caractère
hostile à tout perfectionnement considérable, intellectuel ou social,
par la tendance de la caste prépondérante à consacrer ses immenses
ressources de tous genres au maintien général de sa domination
presque absolue, lorsque elle-même a déjà perdu nécessairement,
sous l'influence prolongée de cette suprématie, la principale
stimulation de son propre développement. Au premier aspect, ce
système politique semble rationnellement très satisfaisant, en ce
qu'il paraît constituer le règne de l'esprit, quoique ce soit, au fond,
encore davantage celui de la peur, puisqu'il repose bientôt sur
l'usage continu des terreurs superstitieuses, et même des divers
prestiges suggérés par une grossière ébauche des connaissances
physiques; à peu près comme si la population était soumise à des
conquérans mieux armés. Mais, par une appréciation plus
approfondie, il importe d'ailleurs de reconnaître franchement, dès
cette première époque, une haute nécessité sociale, suite inévitable
de l'économie fondamentale de la nature humaine, et qui condamne
directement la domination politique de l'intelligence, comme
radicalement hostile à l'accomplissement graduel de notre véritable
évolution. Quoique l'esprit doive spontanément tendre de plus en
plus à la suprême direction des affaires humaines, il ne saurait
certainement y parvenir jamais, par suite de l'extrême imperfection
de notre organisme, où la vie intellectuelle est ordinairement si peu
énergique: en sorte que, dans l'ordre réel, individuel ou social,
l'esprit est seulement destiné à modifier essentiellement la
prépondérance matérielle, par un indispensable office consultatif,
mais sans pouvoir habituellement donner l'impulsion. Or, cette même
intensité trop peu prononcée, qui, quoi qu'on puisse faire, ne peut
aucunement permettre le règne réel de l'intelligence, rendrait, d'une
autre part, cet empire très dangereux, et bientôt hostile au progrès,
si on tentait de l'établir; faute de la stimulation continue dont sa
faiblesse native a tant besoin, et dont cette chimérique domination
ferait nécessairement cesser la principale puissance: l'esprit, né pour
modifier et non pour commander, serait alors essentiellement
employé à maintenir son monstrueux ascendant, au lieu de suivre
noblement sa grande destination au perfectionnement. Je me borne
à indiquer ici cette considération capitale, qui sera naturellement
reprise, au chapitre suivant, d'une manière plus directe et plus
spéciale. Mais elle est ainsi assez signalée déjà pour nous faire
actuellement comprendre, dans sa plus intime profondeur, le vrai
principe élémentaire de cette tendance radicalement stationnaire si
justement reprochée, en général, au système théocratique, par
ceux-là même qui, d'un autre côté, ne pouvaient s'empêcher
d'admirer profondément son apparente rationnalité. En considérant
ensuite, d'un tel point de vue, les divers élémens essentiels de ce
régime initial, chacun pourra aisément y vérifier que cette excessive
concentration des divers pouvoirs, première cause de sa consistance
caractéristique, devenait bientôt un obstacle nécessaire à tout
perfectionnement notable, aucune partie ne pouvant être isolément
améliorée sans compromettre l'ensemble d'un système où régnait
une semblable solidarité. Sous le point de vue scientifique, par
exemple, si vainement présenté comme éminemment favorable aux
théocraties antiques, il est clair que l'esprit humain n'a pu, au
contraire, y dépasser jamais les plus simples progrès, non-seulement
faute d'une stimulation suffisante, mais aussi parce que l'action
critique qui serait naturellement résultée, contre le polythéisme
dominant, d'un développement plus avancé, aurait directement
tendu à bouleverser dès lors toute l'économie sociale. Personne ne
saurait ignorer aujourd'hui que, après le premier ébranlement
mental, les sciences ne pouvaient fleurir que cultivées pour elles-
mêmes, et non comme instrumens de domination politique. Toute
autre partie quelconque du système social pourrait donner lieu à une
appréciation essentiellement analogue, que je dois maintenant
laisser au lecteur. Ainsi, en résumé, on ne peut pas plus contester
l'aptitude fondamentale du polythéisme théocratique à ébaucher, à
tous égards, par une indispensable participation, l'ensemble de
l'évolution humaine, qu'on ne doit, d'un autre côté, méconnaître son
inévitable tendance ultérieure à entraver directement le
développement général. Les peuples chez lesquels la caste militaire
n'a pu parvenir à subalterniser enfin la caste sacerdotale, n'ont donc
joui d'abord d'une mémorable prééminence, que pour se voir ensuite
condamnés à une immobilité presque incurable, à laquelle la
conquête même peut difficilement apporter un assez puissant
correctif, puisque, dans les théocraties les plus fortement
constituées, les vaincus ont spontanément absorbé les vainqueurs,
comme l'histoire nous le montre par tant d'éclatans exemples, où
l'on voit le conquérant étranger se transformer insensiblement en
chef du sacerdoce dirigeant, sans que la nature primitive du régime
en reçoive presque jamais aucune altération capitale: il en était
essentiellement ainsi lorsque, dans les révolutions intérieures, les
guerriers ayant pu prendre momentanément le dessus sur les
pontifes, finissaient bientôt eux-mêmes par acquérir
involontairement le caractère théocratique, ce qui maintenait
toujours l'esprit général du système, sauf un simple changement de
personnes ou de dynasties.
Note 14: Plusieurs philosophes, sous l'inspiration des vaines
théories métaphysiques qui ont tant exagéré, au siècle dernier,
l'influence des signes, ont pensé, surtout envers les Chinois, que
cette immobilité dépendait principalement de l'usage universel de
l'écriture hiéroglyphique, sans réfléchir que d'autres théocraties
voisines, et certes non moins immobiles, n'étaient point assujéties
à cette prétendue cause prépondérante. Quels que soient les
graves inconvéniens sociaux d'une telle écriture, il est clair que
cette superficielle appréciation, d'abord spécieuse, prend
réellement un symptôme pour un principe, puisque cet usage
continue, depuis l'établissement des Tatars, à subsister
conjointement avec la désuétude de l'écriture alphabétique de ces
conquérans. L'ensemble du système théocratique explique certes
assez directement son esprit anti-progressif, pour qu'on doive se
dispenser de recourir à des considérations accessoires et
partielles, hors de toute proportion raisonnable avec les effets
qu'on veut ainsi leur attribuer.

En considérant de plus près le passage général du polythéisme


théocratique au polythéisme militaire, on reconnaît aisément qu'il n'a
pu s'effectuer que chez les peuples où l'ensemble des conditions
extérieures avait empêché le développement de la théocratie, en
favorisant celui de la guerre, et dont la civilisation avait été hâtée
par d'heureuses colonisations qui, essentiellement provenues de
pays soumis au pur régime des castes, ne pouvaient cependant
l'enraciner de nouveau sur un sol mal disposé, un tel transport
devant, en effet, neutraliser beaucoup les dangers politiques de ce
système, sans nuire sensiblement à ses qualités intellectuelles et
morales. L'importante révolution ainsi accomplie communément dans
cette organisation primitive, a partout maintenu, au fond, le principe
des castes, qui se retrouve chez toute l'antiquité, où la naissance a
toujours exercé une influence politique prépondérante, décidant
d'abord habituellement de la liberté ou de l'esclavage, et
déterminant ensuite, en majeure partie, surtout à l'origine, la nature
des attributions de chacun. Mais le principe d'hérédité s'est trouvé
dès lors essentiellement modifié par l'introduction régulière et
permanente d'une certaine faculté de choix d'après une appréciation
personnelle et directe, faculté nouvelle qui, quoique d'abord
étroitement subordonnée à la naissance, a dû ensuite acquérir une
extension et une indépendance toujours croissantes. L'équilibre
politique qui a pu s'établir entre ces deux tendances opposées devait
surtout dépendre du développement plus ou moins parfait de
l'activité militaire, si propre, par sa nature, à mettre en pleine
évidence la supériorité des vraies vocations correspondantes. C'est
ainsi que, chez les Romains, cet équilibre a été bientôt suffisamment
institué, et spontanément maintenu pendant plusieurs siècles, par
une suite nécessaire, quoique indirecte, de l'essor graduel et continu
du système de conquête: tandis que, chez les Grecs, par une cause
inverse, les législateurs et les philosophes avaient été toujours
occupés à organiser laborieusement, entre ce qu'ils nommaient
l'oligarchie et la démocratie, une conciliation durable, sans pouvoir
jamais y parvenir assez.
A partir du polythéisme militaire, l'étude générale de l'évolution
humaine doit être nécessairement décomposée, jusqu'aux temps
modernes, en deux parties essentielles, intimement mêlées
auparavant sous le polythéisme théocratique: car, malgré la
corelation élémentaire qui existe toujours plus ou moins entre la
marche de l'esprit humain et celle de la société, il est certain que dès
lors la principale évolution intellectuelle et la principale évolution
sociale ont été, dans le développement fondamental de l'humanité,
profondément séparées, et produites, en des temps très distincts,
sous des régimes fort différens, quoique radicalement analogues.
Telle est l'origine essentielle de la division historique ci-dessus
annoncée entre le mode grec et le mode romain, à laquelle notre
appréciation doit maintenant se subordonner. C'est aussi pourquoi,
envers chacun de ces deux modes également indispensables, nous
devrons surtout nous réduire à y examiner le développement qui lui
était spécialement réservé, en commençant par le régime grec. Par
cela même que ce premier régime est, à tous égards, intermédiaire
entre le régime égyptien et le régime romain, plus intellectuel que
l'un et moins social que l'autre, il semblerait, d'après un principe
logique déjà heureusement employé dans plusieurs parties
antérieures de ce Traité, que son appréciation rationnelle dût être
plus nettement conçue à la suite de celle des deux termes extrêmes.
Mais, comme le terme initial vient d'être assez caractérisé, et que le
lecteur a déjà sans doute une suffisante connaissance provisoire du
terme final, il est clair que l'avantage philosophique inhérent à un tel
ordre d'exposition ne saurait assez compenser le grave inconvénient
qu'il y aurait à altérer ainsi, quoique seulement dans la forme, la
conception de filiation graduelle, qui doit certainement prédominer
en toute opération historique: ce qui n'empêche pas toutefois que
cette inversion ne puisse ensuite être accessoirement recommandée
au lecteur, à titre d'un utile exercice.
Un coup d'œil philosophique sur l'ensemble de l'histoire grecque,
suffit pour montrer directement que, dans cette société, l'activité
militaire, quoique fondamentale et continue, était toujours réduite à
un essor essentiellement vague et incohérent, sans pouvoir encore
aboutir à sa grande destination sociale, par le développement
graduel d'un système de conquêtes durables, fonction politique
éminemment réservée au régime romain. Suivant l'heureuse
expression de De Maistre, on peut dire en quelque sorte que la
Grèce était née divisée: puisque cet état caractéristique de luttes
intérieures, non moins stériles que continues, entre des peuplades
aussi analogues, a commencé dès la première origine distincte de
cette mémorable population, et n'a cessé que par l'universelle
prépondérance de la domination romaine; si tant est d'ailleurs qu'il
n'en reste point, encore aujourd'hui, des traces très sensibles. La
constitution géographique de la Grèce explique, en partie, cette
division radicale, par l'excessive dissémination qui distingue un tel
territoire, non-seulement dans l'Archipel, mais même sur le
continent, naturellement décomposé en un grand nombre de
portions indépendantes, en vertu des golfes, des isthmes, des
chaînes, etc., dont il est tant traversé. A cette condition extérieure, il
faut joindre, pour compléter suffisamment une telle explication, une
cause sociale non moins essentielle, consistant dans l'identité
remarquable de ces diverses populations, civilisées, presque
simultanément, sous l'influence d'une langue à peu près commune,
par des colonies dont l'origine était semblable et la sociabilité fort
analogue[15]. De ce double caractère fondamental, il est
nécessairement résulté que chacun de ces peuples, d'abord aussi
disposé sans doute que le peuple romain[16] à poursuivre
graduellement la conquête universelle, n'a jamais pu, malgré des
efforts toujours renouvelés, subjuguer finalement ses plus proches
voisins, et a été dès lors forcé d'aller surtout déployer au loin son
ardeur belliqueuse, suivant une marche entièrement inverse à celle
de Rome, et radicalement incompatible avec l'établissement
progressif d'une domination à la fois étendue et durable, susceptible
de fournir un point d'appui vraiment solide au développement
ultérieur de l'humanité. C'est ainsi, par exemple, que la peuplade
athénienne, au moment de sa plus éclatante prépondérance, dans
l'Archipel, en Asie, en Thrace, etc., était réduite à un territoire central
à peine équivalent à un moyen département français, et tout autour
duquel campaient de nombreux rivaux, dont l'assujétissement réel
était alors justement réputé impraticable: Athènes pouvait plus
raisonnablement projeter la conquête, par exemple, de l'Égypte ou
de l'Asie mineure, que celle, non-seulement de Sparte, mais même
de Thèbes ou de Corinthe, ou peut-être de la petite république
adjacente de Mégare; quelque paradoxale que doive d'abord
paraître, à nos esprits modernes, une telle appréciation, elle
n'étonnera point sans doute ceux qui ont vraiment approfondi l'étude
de cette situation politique.
Note 15: Le principe de la colonisation a exercé une influence
tellement capitale sur la destination, essentiellement intellectuelle,
de la civilisation grecque, que l'on peut noter les colonisations
redoublées, ou poussées même au troisième degré, comme ayant
le plus heureusement concouru à l'ensemble du mouvement
spirituel, soit philosophique, scientifique ou esthétique: ainsi que
le témoignent si clairement tant d'éminens exemples analogues à
ceux d'Homère, de Thalès, de Pythagore, d'Aristote même,
d'Archimède, d'Hipparque, etc. On conçoit aisément, en effet, que
les propriétés caractéristiques du régime grec pour exciter
l'évolution intellectuelle, devenaient naturellement d'autant plus
prononcées, dans ces dérivations successives, qu'on s'éloignait
davantage de la source théocratique primordiale, sans cependant
que l'esprit de conquête pût acquérir un plus libre
développement: pourvu toutefois que les altérations ne fussent
pas ainsi poussées au point de dénaturer le système originaire, ce
qui ne pouvait guère arriver tant qu'il y restait quelques rapports
suivis avec la métropole, dont l'ascendant, politique ou moral,
devait y tempérer spécialement l'essor militaire.

Note 16: Il est clair, par exemple, que les Spartiates n'étaient
essentiellement, pour ainsi dire, que des Romains avortés, faute
d'un milieu convenable, admirablement organisés pour la guerre,
et ne pouvant néanmoins conquérir avec fruit. Mais cette
peuplade n'en a pas moins rempli une indispensable fonction dans
le système total de la civilisation grecque, comme propre à
constituer le principal noyau militaire, dans les occasions capitales
où la Grèce devait agir, et surtout résister, collectivement; quoique
son aveugle antipathie contre Athènes l'ait trop souvent conduite,
en ses temps même de plus grande splendeur, à seconder
honteusement les projets hostiles de la théocratie persane, qu'elle
avait, en d'autres cas, si noblement combattue.

Par suite d'une telle position fondamentale, l'activité militaire


avait donc, chez ces peuples, toute l'intensité convenable pour
empêcher le développement, long-temps imminent, du régime
théocratique, auquel l'expulsion ou l'abaissement des rois opposait
partout une puissante barrière politique, en harmonie avec une
antipathie morale très prononcée: mais, en même temps, ces
diverses nations antagonistes, presque équivalentes en puissance
guerrière, devaient se neutraliser essentiellement, de manière à
empêcher cette inquiète activité d'accomplir progressivement sa
grande mission politique. Ainsi, pendant que l'humanité s'y trouvait
préservée de cette torpeur intellectuelle et morale que tend
nécessairement à produire la prolongation démesurée du régime
théocratique, la vie guerrière ne pouvait cependant y acquérir
habituellement assez de prépondérance pour absorber radicalement,
comme à Rome, les principales facultés des hommes éminens,
auxquels ces vaines luttes ne pouvaient sans doute, malgré les
préjugés dominans, inspirer toujours un intérêt exclusif. Telle est la
grande cause qui a rejeté, en quelque sorte, dans la vie
intellectuelle, une énergie cérébrale continuellement excitée, et que
la destination politique ne pouvait suffisamment satisfaire: la même
influence agissant aussi sur les masses, quoiqu'à un degré beaucoup
moindre, les disposait également à goûter convenablement cette
nouvelle culture, surtout quant aux beaux-arts. Cependant, cette
tendance fondamentale n'aurait pu spontanément déterminer le
rapide développement de l'évolution intellectuelle, soit scientifique,
soit esthétique, si les premiers germes n'en eussent été, d'un autre
côté, préalablement empruntés aux sociétés théocratiques, par une
suite naturelle des colonisations originaires. Voilà donc par quel
concours de conditions essentielles il a enfin surgi, dans la Grèce,
une classe libre entièrement nouvelle, qui devait alors servir
d'inappréciable organe au principal essor mental de l'élite de
l'humanité, comme étant à la fois éminemment spéculative, sans
avoir le caractère sacerdotal, et essentiellement active, sans être
absorbée par la guerre. En altérant de quelques degrés, en l'un ou
l'autre sens, cet admirable antagonisme, qui n'a jamais été
nettement conçu, les philosophes, les savans et les artistes
demeuraient de simples pontifes, plus ou moins élevés dans la
hiérarchie sacerdotale, ou devenaient d'humbles esclaves chargés
des soins pédagogiques dans les grandes familles militaires. Mon
illustre prédécesseur, Condorcet, semble avoir entrevu le vrai
principe de cette mémorable situation, mais sans avoir pu l'apprécier
suffisamment, faute d'une saine théorie fondamentale de l'ensemble
de l'évolution humaine. On voit ainsi quel service capital a dès lors
indirectement rendu à l'humanité l'essor continu de l'activité
militaire, quoique politiquement stérile: sans parler d'ailleurs de son
importance spéciale assez connue pour soustraire, à l'envahissement
toujours imminent des immenses armées théocratiques, ce petit
noyau de libres penseurs, alors chargés, en quelque sorte, des
destinées intellectuelles de notre espèce, qui peut-être, sans les
sublimes journées des Thermopyles, de Marathon, et de Salamine,
ultérieurement complétées par l'immortelle expédition du grand
Alexandre, resterait encore, même aujourd'hui, partout plongée dans
l'avilissement théocratique.
Nous aurons maintenant assez apprécié cette grande destination
mentale du régime grec, si nous nous réduisons ici à la considération
sommaire du développement le plus important, c'est-à-dire, de
l'évolution philosophique et scientifique, puisque l'évolution
esthétique a déjà été ci-dessus convenablement caractérisée. Pour
plus de clarté, j'envisagerai d'abord l'essor scientifique, comme le
plus capital en lui-même, à titre de manifestation primordiale d'un
nouvel élément intellectuel, ultérieurement réservé à une
prépondérance définitive, et comme ayant d'ailleurs profondément
influé dès lors sur l'essor simultané de la philosophie proprement
dite.
Envers l'une et l'autre évolution, le point de départ commun
résultait donc de la formation spontanée, il y a moins de trente
siècles, d'une classe éminemment contemplative, composée, en
dehors de l'ordre légal, d'hommes libres, doués d'une haute
intelligence et pourvus du loisir suffisant, sans aucune attribution
sociale déterminée, et, par suite, bien plus purement spéculatifs que
les dignitaires théocratiques, dont l'esprit devait être principalement
occupé à conserver ou à appliquer leur éminent pouvoir. Ces sages
ou philosophes durent d'ailleurs long-temps cultiver simultanément,
à l'imitation de leurs précurseurs sacerdotaux, toutes les parties
quelconques du domaine intellectuel, sauf toutefois l'importante
séparation, presque immédiate, de la poésie et des autres beaux-
arts, en vertu d'un essor plus rapide. Mais cette activité continue dut
tendre ensuite à déterminer graduellement une division nouvelle,
première base directe de notre propre développement scientifique,
lorsque l'esprit positif put enfin commencer à s'y manifester
nettement, avec tous les vrais caractères qui lui appartiennent,
malgré la philosophie, d'abord purement théologique et puis de plus
en plus métaphysique, qui continua nécessairement à présider à
toutes les spéculations de l'antiquité.
Cette apparition décisive du véritable esprit scientifique, s'opéra
alors, comme c'était inévitable, par l'élaboration des idées les plus
simples, les plus générales et les plus abstraites, c'est-à-dire les
idées mathématiques, berceau nécessaire de la positivité rationnelle,
et que ces mêmes caractères devaient d'ailleurs spontanément
soustraire à la juridiction spéciale de la théologie dominante, qui ne
pouvait descendre à de tels détails, seulement enveloppés
implicitement sous son universelle suprématie intellectuelle. Il est
même certain que les idées purement arithmétiques, où ces trois
attributs corelatifs sont encore plus prononcés, furent d'abord le
sujet de certaines recherches mathématiques, quelque temps avant
que la géométrie commençât à se dégager de l'art de l'arpentage,
auquel elle adhérait essentiellement dans les spéculations
théocratiques. Néanmoins, le nom caractéristique de la science, qui,
depuis cette époque, n'a jamais cessé d'être tiré de cette partie
principale, comme il continuera nécessairement à l'être toujours, à
cause de sa prépondérance rationnelle, suffirait uniquement à en
constater la culture presque aussi ancienne, la géométrie
proprement dite devant d'ailleurs seule spontanément fournir un
champ suffisant à l'esprit arithmétique, et surtout à l'esprit
algébrique, qui n'en pouvait d'abord être séparé. Telle fut, chez le
grand Thalès, l'origine de la vraie géométrie, surtout par la formation
de la théorie fondamentale des figures rectilignes, bientôt agrandie
par l'immortelle découverte de Pythagore, qui procéda d'un principe
distinct, d'après la considération directe des aires, quoiqu'elle eût pu,
sans doute, déjà résulter des théorèmes de Thalès sur les lignes
proportionnelles, si la faculté de déduction abstraite avait pu être
alors assez avancée. Le fait célèbre de Thalès enseignant aux
prêtres égyptiens à mesurer la hauteur de leurs pyramides par la
longueur des ombres, constitue, pour quiconque en saisit bien toute
la portée, un immense symptôme intellectuel, permettant d'apprécier
exactement, de part et d'autre, le véritable état de la science,
quelquefois si ridiculement exagéré encore en l'honneur des
théocraties antiques; en même temps qu'il témoigne du progrès
fondamental déjà accompli alors dans la raison humaine, ainsi
parvenue à considérer enfin, sous un simple aspect d'utilité
scientifique, un ordre de phénomènes où elle n'avait si long-temps
envisagé qu'un sujet de terreurs superstitieuses. A partir de cette
grande époque, l'esprit géométrique, bientôt alimenté par l'heureuse
invention des sections coniques, s'élève rapidement jusqu'à
l'éminente perfection qu'il acquiert dans le sublime génie
d'Archimède, type éternel, à tous égards, du vrai géomètre, et
premier créateur de toutes les méthodes fondamentales, d'où
devaient découler les immenses progrès ultérieurs, quoiqu'elles ne
pussent alors avoir que ce caractère de particularité, nécessairement
inhérent à la géométrie ancienne. Il ne faut pas d'ailleurs oublier la
voie entièrement nouvelle ouverte, en outre, par Archimède à l'esprit
mathématique, commençant à embrasser aussi un ordre de
phénomènes plus compliqué, en ébauchant la création de la théorie
rationnelle de l'équilibre des solides, et même, à quelques égards,
des fluides. Enfin, en s'arrêtant encore un peu plus à un si grand
nom, bien digne d'une telle exception, il ne serait pas inutile, à notre
but philosophique, de signaler ici avec quelle plénitude l'esprit
scientifique s'était alors développé, chez son plus pur et plus parfait
organe, en notant aussi l'admirable fécondité de ses applications
pratiques, et surtout la dignité vraiment caractéristique si noblement
manifestée par Archimède, lorsqu'il consentit à se détourner
momentanément de ses éminens travaux pour s'occuper, dans un
grave besoin public, d'un ordre de conceptions aussi secondaire, où
il soutint si hautement sa supériorité, première indication décisive
des immenses services que la science devait rendre un jour à
l'industrie. Après lui, et sauf peut-être Apollonius, il n'y a plus
réellement à considérer, dans l'antiquité, sous le point de vue
purement scientifique, comme génie mathématique vraiment
créateur, que le grand Hipparque, trop peu apprécié, fondateur de la
trigonométrie, spontanément préparée par Archimède, ainsi que je
l'ai expliqué au premier volume, et auquel sont dues toutes les
principales méthodes de la géométrie céleste, dont il avait
essentiellement conçu le véritable ensemble, et d'avance constitué
même les relations pratiques fondamentales, soit à la connaissance
des temps, ou à celle des lieux. Hors des diverses spéculations
mathématiques, il ne pouvait alors certainement exister aucune
sphère d'activité convenablement préparée pour le véritable esprit
scientifique, comme l'ensemble de ce Traité l'a déjà
surabondamment démontré, et comme l'indique d'ailleurs
spontanément le nom même déjà imposé à cette science
primordiale, et qui rappelle si naïvement son exclusive positivité à
cette époque. Quel que soit, en réalité, l'éminent mérite individuel
manifesté, sous ce rapport, par les travaux d'Aristote sur les
animaux, et même antérieurement par les éclairs du génie médical
d'Hippocrate sur l'étude générale de la vie, la situation fondamentale
de l'esprit humain n'en pouvait être essentiellement changée, au
point de rendre déjà vraiment possibles des sciences aussi
profondément compliquées, dont la création systématique devait
être si évidemment réservée à un avenir alors extrêmement lointain.
Bien que la nature de notre opération doive nécessairement
interdire ici toute poursuite ultérieure d'un tel développement
spécial, j'ai cependant jugé indispensable d'insister sur ce premier
essor caractéristique de la positivité rationnelle, pour y marquer
l'introduction spontanée de ce grand modificateur graduel de la
philosophie primitive, avec son double attribut, spéculatif et abstrait,
indispensable à son évolution ultérieure, et déjà si purement
prononcé dans cet essai décisif. Il importe aussi de noter, à ce sujet,
le génie éminemment spécial qui, dès l'origine, commence
inévitablement à distinguer ce nouvel ordre de spéculations, par
opposition aux contemplations indéterminées de l'ancienne
philosophie. Quoique la spécialité, devenue aujourd'hui exorbitante
et exclusive, puisse être maintenant, à divers égards, très
dangereuse pour l'ordre social, depuis que le besoin de généralités
nouvelles est directement prépondérant, il n'en pouvait être
aucunement ainsi en un temps où, exercée en dehors d'un système
de sociabilité, qui devait, long-temps encore, reposer sur d'autres
bases, elle n'était évidemment susceptible d'aucun grave
inconvénient politique, et constituait, au contraire, l'unique moyen
qui, indépendamment de la commune nécessité de la répartition des
travaux, pût enfin apprendre à l'esprit humain, d'abord dans les cas
les plus simples, à approfondir convenablement un sujet quelconque,
ce qui jusque-là était resté radicalement impossible. En un mot,
l'esprit scientifique, alors nullement constituant, et destiné
seulement à préparer de très loin, sous le régime théologique, le
principal élément ultérieur du régime positif, devait être, sans aucun
danger social, éminemment spécial, sous peine d'avortement
inévitable: ce qui ne saurait signifier d'ailleurs que la même
disposition doive rester indéfiniment prépondérante, quand les
besoins et la situation ont radicalement changé, comme le croient,
avec une si aveugle obstination, presque tous les savans actuels. On
ne peut douter, en effet, que les savans proprement dits n'aient
commencé à paraître, déjà nettement séparés des philosophes, et
avec leurs principaux attributs modernes, à partir de cette
mémorable époque, si hautement caractérisée, sous ce rapport, par
l'admirable fondation du musée d'Alexandrie, directement destinée à
satisfaire ce nouveau besoin intellectuel, après le triomphe
irrévocable du polythéisme progressif sur le polythéisme
stationnaire.
Quant à l'évolution purement philosophique, elle présente,
surtout avant cette indispensable séparation, des traces très
sensibles de l'influence secrète de cette positivité naissante pour
modifier déjà radicalement, par l'intervention prononcée de la
métaphysique, le système général de la philosophie théologique,
suivant la marche élémentaire indiquée au chapitre précédent,
d'après ma théorie fondamentale du développement mental. Avant
même que les études astronomiques pussent commencer à dévoiler,
sur des phénomènes unanimement observés, l'existence directe des
lois naturelles proprement dites, on voit l'esprit humain, impatient
d'échapper prématurément au régime franchement théologique,
s'efforcer d'aller puiser, dans l'essor rudimentaire des conceptions
mathématiques, des idées universelles d'ordre et de convenance,
qui, malgré leur caractère profondément confus et nécessairement
chimérique, constituent réellement un vague pressentiment initial de
la subordination ultérieure de tous les phénomènes à des lois
naturelles. Cet emprunt fondamental de la philosophie à la science,
première base véritable de toute la métaphysique grecque, a
d'ailleurs suivi, dès cette époque, la marche nécessaire de l'esprit
mathématique, passant de l'arithmétique à la géométrie; puisque
ces mystères philosophiques, d'abord exclusivement relatifs aux
nombres, s'étendirent ensuite aux figures, sans cesser toutefois,
jusqu'aux derniers efforts de la subtilité grecque, d'embrasser
simultanément ces deux ordres d'idées: ce qui me semble
éminemment propre à justifier cette nouvelle appréciation historique
d'une telle philosophie, dont l'œuvre immense du grand Aristote
constituera toujours le plus admirable monument, éternel
témoignage de la puissance intrinsèque de la raison humaine, à
l'état même d'extrême imperfection spéculative, appréciant à la fois,
avec une profonde sagacité, autant que l'époque le comportait, les
sciences et les beaux-arts, et n'exceptant, de sa vaste conception
encyclopédique, que les seuls arts industriels, alors crus indignes des
hommes libres. Après la séparation décisive opérée par
l'établissement alexandrin, cette philosophie, irrévocablement divisée
en naturelle et morale, passe, de l'essor purement spéculatif, à une
existence sociale de plus en plus active, en s'efforçant d'influer
désormais toujours davantage sur le gouvernement de l'humanité,
dont la suprême direction future n'arrête même point ses
ambitieuses utopies. Quelques étranges aberrations qu'ait dû
produire cette nouvelle phase, elle n'était pas, au fond, moins
nécessaire que la première à la préparation générale du régime
monothéique, non-seulement en accélérant l'universelle décadence
du polythéisme, mais aussi comme instituant, à l'insu même de tous
les philosophes, un germe indispensable de réorganisation
spirituelle, comme je l'expliquerai bientôt. On peut même apercevoir
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookultra.com

You might also like