Professional Documents
Culture Documents
Master AccessSQL
Master AccessSQL
Master AccessSQL
1/22/2003 (Last Updated) A ---------------------------------A Application object prop/methods Automating compaction (by User)
Automation of Excel Automation of Word Automation of Word (simple ex.) B ---------------------------------B
Bookmarks C ---------------------------------C Calculated controls--ControlSource Capitalize (capitalize certain field)
Clones (RecordsetClone) Closing a database connection Closing a form Collection (ways of referencing)
Column (listing single one) Combo Box properties/methods Combobox Load with SQL Query Combobox Update & Item Selection
Compaction (automating for User) Concatenation function (simple) Containers (& docs within) listing Control object properties/methods
Control Source properties (Access) Controls (moving to specific ones) ControlSource data (separate form) D ---------------------------------D
Data Conversion functions Database (creating new one) Database Connection (example) Database properties (determining)
Date calc (diff between 2 dates) Declaring a Recordset Object Declaring Database Connection DLookup function (data f tbl or q)
DoCmd object Domain Aggregate functions E ---------------------------------E Error Table creation
Excel (link spreadsheet as a table) Excel chart creation via automation F ---------------------------------F Field (i.e., Column) Constraints
Field (listing single col in recordset) File Open dialog (for choosing file) Filename & Path Info (of dbase) Finding record (simple form)
Finding record (via seek method) Finding records (walking recordset) Finding recs (FindFirst & FindNext) Finding recs (seek against table)
Finding recs (SQL search -- pref.) Finding recs (SQL string - simple) Finding recs (using no-match prop) Focus (giving a control focus)
Form activation (from another) Form object properties/methods Form Open? (true or false) Form open? check (IsLoaded funct.)
FoxPro (creating FoxPro table) FoxPro (linking to a FoxPro db) Functions (rules for calling/using) G ---------------------------------G
H ---------------------------------H Hourglass (turning it on) HTML Output (example) I ---------------------------------I
IsLoaded utility (Form open?) J ---------------------------------J K ---------------------------------K L ---------------------------------L
List box properties/methods ListBox Item Selection Listbox: rowsource from SQL query M ---------------------------------M
Me property (when within object) Module object propeties/methods N ---------------------------------N Null strings in database fields
O ---------------------------------O Opening a database connection Opening a Form (simple method) Opening a Recordset
Opening and Closing a Form Opening form (hiding & returning) Opening form (in data entry mode) Outlook (sending invoice reminder)
P ---------------------------------P Password (how to change it) Printing reports example Progress meter in status bar
Properties of a database (finding) Properties/Methods: Application Properties/methods: Combo & List Properties/methods: Controls
Properties/Methods: Form object Properties/methods: Report object Q --------------------------------- QueryDef (constructing w VBA)
QueryDef (editing with VBA) R ---------------------------------R Record locking types & method Record navigation (in database/rst)
Records Found with SQL to Array Recordset (rows & cols) into Array Recordset (Working With) Recordset Open Options
Refresh table links Report (after Query mod by listbox) Report object properties/methods Rowsource of listbox from SQL
S ---------------------------------S Security (adding a Group Account) Security (adding a User Account) Security (adding User to Group)
Security (granting read only) Security (list groups & users) Security (list Groups in workspace) Security (listing permissions)
Security (show "no delete" perms) Show/Hide Controls Spreadsheet (linking an Excel sht) SQL (changing display of NULL)
SQL (conditional CASE logic) SQL (converting datatypes) SQL (handling dates) SQL (handling upper- & lowercase)
SQL (list of commands/keywords) SQL (pattern-matching) SQL (string concatenation) SQL (substring SUBSTR function)
SQL Aggregate functions SQL cmd to delete a table SQL cmds to append data to table SQL cmds to change table data
SQL cmds to create a table SQL cmds to delete rows f table SQL Query (Basic Form) SQL Query (joining tables on field)
SQL Statement (Full Syntax expl.) Sub Procedures (rules for using) Synchronizing forms SysCmd function (object states, etc.)
T ---------------------------------T Table Creation (using SQL) Table creation using VBA Tag property (available for use)
Timer function (timing a process) Transaction process (example) U ---------------------------------U Unhiding previously hidden object
Userform_Initialize equivalent Users (list all Users in workspace) Users (list users & groups o) V ---------------------------------V
Variables Variables & Procedures VBE Shortcuts View Creation (SQL)
W ---------------------------------W Walking recordset (faster!) Walking the recordset Word automation (creating letter)
Word automation (simple example) X --------------------------------- Y ---------------------------------Y Z ---------------------------------
******************************************************************************************************
******************************************************************************************************
******************************************************************************************************
******************************************************************************************************
******************************************************************************************************
******************************************************************************************************
******************************************************************************************************
******************************************************************************************************
******************************************************************************************************
******************************************************************************************************
Walking recordset (faster!)
******************************************************************************************************
Here is a trick to loop through a recordset faster. Often when looping through a recordset people will use the
following code:
Do while not records.eof
combo1.additem records![Full Name]
records.movenext
Loop
The problem is that everytime the database moves to the next record it must make a check to see if it has reached the
end of the file. This slows the looping down a great deal. When moving or searching throuch a large record set this
can make a major difference. Here is a better way to do it.
records.movelast
lngRecCount=records.RecordCount
records.movefirst
For lngCounter=1 to lngRecCount
combo1.additem records![Full Name]
records.movenext
Next lngCounter
******************************************************************************************************
Null strings in database fields
******************************************************************************************************
Dealing with Null strings in Access database fields
By default Access string fields contain NULL values unless a string value (including a blank string like "") has been assigned. When you read
these fields using recordsets into VB string variables, you get a runtime type-mismatch error. The best way to deal with this problem is to use
the built-in & operator to concatenate a blank string to each field as you read it. For example:
Dim DB As Database
Dim RS As Recordset
Dim sYear As String
Set DB = OpenDatabase("Biblio.mdb")
Set RS = DB.OpenRecordset("Authors")
sYear = "" & RS![Year Born]
******************************************************************************************************
Password (how to change it)
******************************************************************************************************
Private Sub ChangeAccessPassword()
Dim Db As Database
Keywords
ALL ALTER COLUMN ALTER SESSION SET EVENTS ANALYZE
ANY AS ASC AUTOTRACE ON AVG
BEGIN BETWEEN CASE CAST CHAR
CHECK COALESCE COLLATE COLLATION FROM COMMIT
CONNECT CONSTRAINT CONVERT COUNT CREATE CHARACTER SET
CREATE RULE CREATE SCHEMA CROSS JOIN CURRENT DATE DATABASE
DATEADD DATEDIFF DATEFORMAT DATEPART DDL
DECIMAL DECODE DEFAULT DESC DISTINCT
DML DOUBLE DOUBLE PRECISION DROP COLLATION ESCAPE
EXISTS EXPLAIN PLAN FLOAT FOREIGN KEY FROM
FULL OUTER GO GROUP BY HAVING IN
INNER INSERT INTO INT INTEGER INTERSECT
INTERVAL IS NULL ISNULL JOIN LEFT OUTER
LENGTH LIKE LONG LONG VARCHAR LOWER
MAX MIN MIN MINUS MODIFY
NATURAL JOIN NESTING NOT NOT BETWEEN NOT EXISTS
NOT IN NOT LIKE NOT NULL NULL AND
NUMBER NUMERIC NVL OR ORDER BY
PRIMARY KEY PUBLIC REAL REFERENCES RIGHT OUTER
ROLLBACK SMALLFLOAT SMALLINT SP_HELPSORT SUBSTRING
SUM SUM TEXT TIME TIMESTAMP
TINYINT TO TO_CHAR TO_NUMBER UNIQUE
UPPER USE VALUES WHERE WITH CHECK OPTION
******************************************************************************************************
SQL (handling dates)
*****************************************************************************************************
One simple way for finding all rows entered on one day is to spell out the full minimum and maximum time values for the day and use
BETWEEN to find everything within those parameters:
SELECT price, pubdate
FROM titles
WHERE pubdate between 'Oct 21 1998 00:00' and 'Oct 21 1998 23:59'
Another idea is to use the keyword LIKE to find everything that matches the known part of the date. Here the % wildcard (similar to an
asterisk) stands for anything following the character string.
SELECT price, pubdate
FROM titles
WHERE pubdate like 'Oct 21 1998%'
You could also use convert functions to change the date into a shorter character string and then search for the string:
SELECT price, pubdate
FROM titles
WHERE cast (pubdate as char(11)) = 'Oct 21 1998'
A particular date function available on some systems is DATEPART which works like this:
SELECT price, pubdate
FROM titles
WHERE datepart(mm, pubdate) = 10 and
datepart(dd, pubdate) = 21 and
datepart(yy, pubdate) = 1998
A similar function is DATEADD which is set up to add a number of time units to a known date -- and you can then retrieve records
between the paramaters without worrying about the time.
SELECT price, pubdate
FROM titles
WHERE pubdate between 'Oct 21 1998' and dateadd(day, 1, 'Oct 21 1998')
There are also situations where you'll want to group data by time units. For example, what's the distribution of books published during the
year (by month)?
SELECT datepart(month, pubdate), count(title_id)
FROM titles
GROUP BY datepart(month, pubdate)
******************************************************************************************************
Rowsource of Listbox from Instream SQL
******************************************************************************************************
MySQL = "SELECT DISTINCT qryPubReviewInfo.AuthorName " & vbCrLf
MySQL = MySQL & "FROM tblComments RIGHT JOIN qryPubReviewInfo ON tblComments.ReviewID = qryPubReviewInfo.ReviewID "
& vbCrLf
MySQL = MySQL & "ORDER by 1;"
lblNames.Caption = "Select Author from list below:"
lblNames.Visible = True
With lstNames ' And sets a few other options for the listbox
.ColumnCount = 1 ' Two columns
.ColumnHeads = False ' With column headings
.RowSource = MySQL ' Providing it the SQL string
.Visible = True ' Turning it on
.Requery ' Requerying it -- just in case we are coming back after being elsewhere on the form
End With
******************************************************************************************************
SQL (handling upper- & lowercase chars)
******************************************************************************************************
Sometimes data is stored in uppercase letters, sometimes in lowercase letters, and sometimes in mixed case. This might reflect the lack of
control over the data as it was entered into the system. This can be handled by:
(1) Using character-classes with the like keyword -- for each character. Example:
SELECT title
FROM titles
WHERE title LIKE '%[Ww][Ii][Tt][Hh][Oo][Uu][Tt]%'
(2) Converting the case to UPPER or LOWER, then performing the comparison:
SELECT title
FROM titles
WHERE UPPER(title) LIKE '%WITHOUT%'
******************************************************************************************************
SQL (converting datatypes)
******************************************************************************************************
You can also use SQL to convert data from one type to another. For example, if you have a number which might be expressed as a decimal
(85.45) but need to express it as a percentage -- you can CAST multiple by 100, then cast it as an integer. Example:
CAST (royaltyshare * 100 as int) || '%' as percent
******************************************************************************************************
SQL (string concatenation ||)
******************************************************************************************************
The double-pipe || allows you to concatenate expressions. The syntax is: char_expr || char_expr
NOTE: Some systems use the plus (+) or period (.) for concatenation.
Several examples:
SELECT au_fname || au_lname as Writer
FROM authors
WHERE state > 'CA'
Output might look like:
Writer
AlbertRinger
AnnRinger
MichaelFrance
SylviaPanteley
We can be creative and use a combination of the SUBSTR and concatenate command to provide the first initial and last name as with:
SELECT SUBSTR(au_fname, 1, 1) || '.' || ' ' || au_lname as Writer
FROM authors
WHERE state > 'CA'
Output would now look like:
Writer
A. Ringer
A. Ringer
M. France
S. Panteley
******************************************************************************************************
SQL (substring SUBSTR function)
******************************************************************************************************
A single field (i.e., column) can be broken into multiple columns -- with the substring SUBSTR command (much as with VBA or PERL).
The syntax is: SUBSTR( expression, start, length) though length is optional -- will simply take rest of expression if left blank.
For example:
SELECT SUBSTR(title_id, 1, 2) as alpha,
SUBSTR(title_id, 3, 4) as num,
SUBSTR(title_id, 3) as no3rd,
SUBSTR(title_id, -4) as countback
FROM titles
WHERE price > 29.99
CASE
WHEN condition1 THEN result1
[WHEN condition2 THEN result2]. . . [ELSE resultn]
END
Example:
SELECT title_id, substr(title, 1, 25) as book,
CASE contract
WHEN 1 THEN 'contract on file'
WHEN 0 THEN 'no contract'
END as contract
FROM titles
ORDER BY title_id
***** A more complex example ********
In this example, you produce a report that compares sales date and ship date and prints notes depending on the difference. (In this
particular implementation the DATEDIFF command takes 3 arguments, though this can vary from system to system).
NOTE: In both the above examples, the CASE statement could be compressed into an element of the SELECT clause.
******************************************************************************************************
Report (after Query modified by Listbox)
******************************************************************************************************
Private Sub cmdProceed_Click()
If Me.Tag = "Individual" Then
For i = 0 To lstNames.ListCount - 1
If lstNames.Selected(i) = True Then
MySelectedEditor = lstNames.Column(1, i) ' Provides the Editor number of selected row into Global Variable
GoTo SKIP_ERROR
End If
Next
MsgBox "You didn't select anyone!" & vbCrLf & vbCrLf & _
"Please TRY AGAIN!", vbCritical + vbOKOnly, _
"INDIVIDUAL SELECTION ERROR"
SKIP_ERROR:
IndividualStats MySelectedEditor ' SUBROUTINE to Modify the Query Definition & Open the Report
ElseIf Me.Tag = "Teams" Then
For i = 0 To lstNames.ListCount - 1
If lstNames.Selected(i) = True Then
MySelectedTeam = lstNames.ItemData(i)
GoTo SKIP_ERROR2
End If
Next
MsgBox "You didn't select a team!" & vbCrLf & vbCrLf & _
"Please TRY AGAIN!", vbCritical + vbOKOnly, _
"TEAM SELECTION ERROR!"
SKIP_ERROR2:
TeamStats MySelectedTeam ' SUBROUTINE to Modify the Query Definition & Open the Report
End If
End Sub
Note: Moving the focus to a specific control on a subform requires using the GoToControl method twice -- you move the focus to the
subform control with the first method and then to the control on the subform with the second method. For Example:
Private Sub cmdToControlOnSubform_Click()
Dim strControl as String, strSubformControl as String
strControl = "Discount"
strSubformControl = "Orders Subform"
DoCmd.GoToControl strSubformControl
DoCmd.GoToControl strControl
End Sub
Note: Moving the focus to a specific control on an open form that isn't active also takes two steps, the first step uses the SelectObject
method of the DoCmd object to activate the open form, and the second step uses the GoToControl method to move to the control. Example:
Private Sub cmdToOtherFormControl_Click()
Dim strControl as String, strOtherForm as String
strOtherForm = "Employees"
strControl = "Title"
DoCmd.SelectObject acForm, strOtherForm
DoCmd.GoToControl strControl
End Sub
[Caution! Anticipate the possibility that a form might be closed by using the IsLoaded() function to check, because attempting to
move focus to a control on a closed form will generate a rather nasty Access error!]
(b) The second method of moving the focus to a specific control on the active form uses the object's SetFocus method.
Example:
object.SetFocus ' rather simple
The SetFocus method of the Control object moves the focus to the specified control on the active form or the specified field on the
active datasheet. When the object is the Form object, the result depends on whether the form has any controls that can receive
the focus: Enabled property must be set to True; otherwise, the SetFocus method moves the focus to the form, itself. Examples:
Private Sub cmdSetControl_CLick()
Dim cbo as ComboBox
Set cbo = Forms!Orders!EmployeeID ' Initializing an object variable to hold our combobox -- speeds execution!
cbo.SetFocus ' Moves focus to the Combobox on the active form.
End Sub
Private Sub cmdSetOtherFormControl_Click() ' Basically the same except that we going to an inactive form rather
Dim frm as Form, txt as TextBox ' than to a subform (as above)
Set frm = Forms![Employees]
Set txt = Forms![Employees]!Extension
frm.SetFocus
txt.SetFocus
End Sub
******************************************************************************************************
Synchronizing Forms
******************************************************************************************************
Private Sub cmdViewCustomer_Click() ' A command button on the Orders form to view the record for this customer
Dim strForm as String
Dim strWhere as String
strForm = "Customers" ' The form we want to open
strWhere = "CustomerID = " & Chr(39) & Forms!Orders!CustomerID & Chr(39) ' Referencing the field on which to sync
DoCmd.OpenForm FormName:=strForm, WhereCondition:=strWhere ' Passing the particular value in the field to same field
End Sub
<< See also pages 473 et seq. in Access 2002 VBA Handbook for more in depth discussion. Such as keeping the forms synchronized,
closing one form from another form, etc. >>
******************************************************************************************************
Opening a Form (hiding & returning)
******************************************************************************************************
Public Function OpenHide (strName as String) ' A generic function to place in the standard module
Dim strHide as String
strHide = Screen.ActiveForm.Name ' Stores name of active form in the variable
Screen.ActiveForm.Visible = False ' Hides the active form
DoCmd.OpenForm strName ' Opens the form which name was passed to the function
Screen.ActiveForm.Tag = strHide ' Sets the Tag property available on all forms to the variable name of originating form
End Function
Public Function CloseUnhide()
Dim strUnhide as String
If IsNull(Screen.ActiveForm.Tag) Then ' The form could have been opened directly, so the property would be empty
DoCmd.Close
Else
strUnhide = Screen.ActiveForm.Tag ' Reading the property
DoCmd.Close ' Closing the Active form
DoCmd.SelectObject acForm, strUnhide ' Unhiding the previously hidden form -- note: it was already open!
End If
End Function
******************************************************************************************************
SysCmd function
******************************************************************************************************
The SysCmd function is actually 3 functions in one. You can use it to:
Return the state of a Database window object
A common use of the SysCmd function is to determine the state of a database object -- whether the object (such as a table,
query, form, report, data access page) is open, whether the object is new, or whether the design of the object has been changed
but not yet saved. The syntax is:
returnvalue = SysCmd(acSysCmdGetObjectState, objecttype, objectname)
The problem is that everytime the database moves to the next record it must make a check to see if it has
reached the end of the file. This slows the looping down a great deal. When moving or searching throuch a
large record set this can make a major difference. Here is a better way to do it.
records.movelast
lngRecCount=records.RecordCount
records.movefirst
For lngCounter=1 to lngRecCount
combo1.additem records![Full Name]
records.movenext
Next lngCounter
******************************************************************************************************
Properties and Methods of Application object
******************************************************************************************************
Some additional properties of the Application object are:
BrokenReference (Read-only; boolean) ' Checks to see if the project contains any broken references to databases or type libraries.
CodeContextObject (Read-only; object) ' Determines the object in which a VBA procedure is running.
CurrentObjectName (Read-only; string) ' Use to determine which database object has the focus, or in which object is running code or
has the focus.
CurrentObjectType (Read-only; integer) ' Returns the object type of the object that currently has the focus.
FeatureInstall (Read/write; enum const) ' Determines how to handle situations in which calls are made to methods and properties that
require features not yet installed.
IsCompiled (Read-only; boolean) ' Determines whether all the modules in the project are in a compiled state. Returns True if all
the modules are in a compiled state.
VBE (Read-only; VBE object) ' Represents the VBA editor and can be used to return a reference to the VBA editor object and
its related properties.
Visible (Read/write; boolean) ' Shows or hides the Access application. If the Visible property is True, the application is visible;
otherwise, the application isn't visible. When the user starts Access, the Visible property is True
and can't be changed. When another application using Automation starts Access, the Visible
property is False by default. You can set this property in a VBA procedure only when the
application is started by another application using Automation (and when the UserControl
property value is False).
tdf.Fields.Append fldCustID
tdf.Fields.Append fldCustName
tdf.Fields.Append fldCustAddress
tdf.Fields.Append fldCustCity
tdf.Fields.Append fldCustState
tdf.Fields.Append fldCustZip
idxCustID.Fields.Append fldCustIDIX
idxCustID.Unique = True
tdf.Indexes.Append idxCustID
db.TableDefs.Append tdf
End Sub
******************************************************************************************************
FoxPro (linking to a FoxPro database)
******************************************************************************************************
Sub LinkTable()
End Sub
******************************************************************************************************
Finding records (SQL string -- simple ex.)
******************************************************************************************************
NOTE: This example searches the "CategoryID" field within the table "Categories" for any CategoryID's greater than or equal to 1.
Then lists the result in the immediate window.
Private Sub CheckSQL() ' A made up name for my subroutine to run the function
Call BuildSQL("1") ' Passing the function the criteria -- could make this more flexible!
End Sub
SQLString = "SELECT * FROM Categories WHERE CategoryID >= " & Criteria ' The SQL search string
Set MyDB = CurrentDb
Set MyRecSet = MyDB.OpenRecordset(SQLString) ' Creating a recordset using the SQL string
While Not MyRecSet.EOF
Debug.Print MyRecSet!CategoryID & ": " & MyRecSet!CategoryName ' Looping through the created recordset and outputing value
MyRecSet.MoveNext
Wend
MyRecSet.Close ' Closing the recordset
Set MyRecSet = Nothing ' Eliminating the object variable
Set MyDB = Nothing ' Eliminating the other object variable
End Function
******************************************************************************************************
Transaction process (example)
******************************************************************************************************
Sub ChangeTitle()
Dim strName As String, strMessage As String, strPrompt As String
Dim wspDefault As Workspace, dbsNorthwind As Database
Dim rstEmployees As Recordset
strPrompt = "Change title to Account Executive?"
Set wspDefault = DBEngine.Workspaces(0) ' Get default Workspace.
Set dbsNorthwind = wspDefault.Databases(0) ' Get current database.
Set rstEmployees = dbsNorthwind.OpenRecordset("Employees", dbOpenTable) ' Open table.
wrdApp.Visible = True
With wrdDoc
.Range.InsertBefore "Hello there everyone!"
.SaveAs "C:\Greetings.doc"
End With
' trims off the db filename so the path is all that's left.
tempPath = Left(MyDB.Name, (Len(MyDB.Name) - FileLen))
' Return the path name
GetDBPath = tempPath
End Function
******************************************************************************************************
Security (granting read permission to User)
******************************************************************************************************
'Grant read permissions only to a table for a specific user
Sub GrantReadPermissions()
Dim Db As Database
Dim doc As Document
Set Db = CurrentDb()
Set ws = DBEngine.Workspaces(0)
With ws
.Groups.Refresh
.Users.Refresh
End With
Set ws = DBEngine.Workspaces(0)
With ws
.Groups.Refresh
.Users.Refresh
End With
End Sub
******************************************************************************************************
Users (list all Users in workspace)
******************************************************************************************************
Option Compare Database
Option Explicit
Set ws = DBEngine.Workspaces(0)
ws.Users.Refresh
For Each usr In ws.Users
Debug.Print "User: " & usr.Name
Next usr
End Sub
Set ws = DBEngine.Workspaces(0)
ws.Groups.Refresh
For Each grp In ws.Groups
Debug.Print "Group: " & grp.Name
Next grp
End Sub
******************************************************************************************************
IsLoaded Utility (to check if Form is open)
******************************************************************************************************+
Option Compare Database
Option Explicit
Const conObjStateClosed = 0
Const conDesignView = 0
End Function
******************************************************************************************************
Word automation (creating a credit letter)
******************************************************************************************************
Option Compare Database
Option Explicit
' close up
objDoc.SaveAs "C:\BegVBA\CredLet"
objDoc.Close
objWord.Quit
recContact.Close
Set objDoc = Nothing
Set objWord = Nothing
End Sub
' select the required bookmark, and set the selection text
objD.Bookmarks(strBkmk).Select
objW.Selection.Text = varText
End Sub
******************************************************************************************************
Outlook (sending an invoice reminder)
******************************************************************************************************
Option Compare Database
Option Explicit
End With
End Sub
End Function
******************************************************************************************************
Refresh Table Links
******************************************************************************************************
Public Function RefreshTableLinks(strDB As String) As Integer
'
' Purpose: To relink the tables from a database
' Arguments: strDB The database to link from
' Returns: True if the tables were linked sucessfully,
' False otherwise
'
Dim dbCurrent As Database ' current database
Dim tblLinked As TableDef ' current table in collection
RefreshTableLinks = True
RefreshTableLinks_Exit:
Exit Function
RefreshTableLinks_Err:
MsgBox Error$
RefreshTableLinks = False
Resume RefreshTableLinks_Exit
End Function
******************************************************************************************************
Excel (link a spreadsheet as if a table)
******************************************************************************************************
Public Sub LinkSpreadsheet()
'
' Purpose: To link a spreadsheet into Access
' Arguments: none
' Returns: none
' This links the spreadsheet into Access as though it was a table
DoCmd.TransferSpreadsheet acLink, acSpreadsheetTypeExcel97, "WhiskySales", _
"C:\BegVBA\WhiskySales.XLS"
End Sub
******************************************************************************************************
Table creation using VBA
******************************************************************************************************
Sub MakeATable()
'
' Purpose: Demonstrates creating a table
' Arguments: none
' Returns: none
'
Dim db As Database
Dim tbl As TableDef
Dim fld As Field
Dim idx As Index
'Start by opening the database
Set db = CurrentDb()
fld.OrdinalPosition = 1
fld.Attributes = dbAutoIncrField
tbl.Fields.Append fld
fld.OrdinalPosition = 2
fld.Size = 50
fld.Required = True
fld.AllowZeroLength = False
tbl.Fields.Append fld
idx.Primary = True
idx.Required = True
idx.Unique = True
End Sub
******************************************************************************************************
QueryDef (editing a query def via VBA)
******************************************************************************************************
Function ChangeQueryDef(strQuery As String, strSQL As String) As Boolean
'
' Purpose: Demonstrates editing a querydef
' Arguments: strSQL The SQL string for the querydef
' Returns: True
If strQuery = "" Or strSQL = "" Then Exit Function
ChangeQueryDef = True
End Function
******************************************************************************************************
QueryDef (constructing using VBA)
******************************************************************************************************
Function MakeQueryDef(strSQL As String) As Boolean
'
' Purpose: Demonstrates creating a querydef
' Arguments: strSQL The SQL string for the querydef
' Returns: True
MakeQueryDef = True
End Function
******************************************************************************************************
Finding records (SQL search -- preferred method)
******************************************************************************************************
Sub FindBottleByPrice2(curPrice As Currency)
'
' Purpose: Demonstrates preferred way to extract restriction of data
' Arguments: none
' Returns: none
'
Dim db As Database
Dim rec As Recordset
Dim strSQL As String
Dim strMatches As String
Dim intCounter As Integer
Set db = CurrentDb()
Set rec = db.OpenRecordset(strSQL, dbOpenSnapshot)
Do Until rec.EOF
strMatches = strMatches & Chr$(10) & rec!BottlingID
rec.MoveNext
Loop
intCounter = rec.RecordCount
rec.Close
End Sub
******************************************************************************************************
Finding records (FindFirst & FindNext methods)
******************************************************************************************************
Sub FindBottleByPrice(curPrice As Currency)
'
' Purpose: Demonstrates use of FindFirst and FindNext methods
' Arguments: none
' Returns: none
'
Dim db As Database
Dim rec As Recordset
Dim strSQL As String
Dim strMatches As String
Dim intCounter As Integer
strSQL = "Bottling"
Set db = CurrentDb()
Set rec = db.OpenRecordset(strSQL, dbOpenSnapshot)
rec.Close
End Sub
******************************************************************************************************
Finding recs (using no-match property)
******************************************************************************************************
Sub SeekPrice2(curPrice As Currency)
'
' Purpose: Demonstrates use of NoMatch property
' Arguments: none
' Returns: none
'
Dim db As Database
Dim rec As Recordset
Dim strSQL As String
Dim strMsg As String
strSQL = "Bottling"
Set db = CurrentDb()
Set rec = db.OpenRecordset(strSQL)
rec.Index = "Price"
rec.Seek "=", curPrice
MsgBox strMsg
rec.Close
End Sub
******************************************************************************************************
Finding records (seek method against table)
******************************************************************************************************
'
' Purpose: Demonstrates use of Seek method against table-type
' Recordset objects
' Arguments: none
' Returns: none
Dim db As Database
Dim rec As Recordset
Dim strSQL As String
Dim strMsg As String
strSQL = "Bottling"
Set db = CurrentDb()
Set rec = db.OpenRecordset(strSQL)
rec.Index = "Price"
rec.Seek "=", curPrice
strMsg = "Bottling No. " & rec("BottlingID") & " costs " & _
Format$(rec("Price"), "Currency")
MsgBox strMsg
rec.Close
End Sub
******************************************************************************************************
Opening a Recordset
******************************************************************************************************
Sub OpenWhiskyRecordset()
'
' Purpose: Demonstrates use of OpenRecordset method
' Arguments: none
' Returns: none
'
Dim db As Database
Dim rec As Recordset
Set db = CurrentDb()
Set rec = db.OpenRecordset("Whisky")
Stop
rec.Close
End Sub
******* 2nd method shown below -- basically the same with a message box showing the record count ****
Dim db As Database
Dim rec As Recordset
Set db = CurrentDb()
Set rec = db.OpenRecordset(strTable)
End Function
******************************************************************************************************
Containers (and documents within) listing
******************************************************************************************************
Public Sub ListContainers()
'
' Purpose: Demonstrate the use of the Containers collection
' Arguments: none
' Returns: none
'
Dim dbCurrent As Database ' current database
Dim conTest As Container ' Container object
Dim docTest As Document ' Document object
Dim objTest As Control ' Control object
Next
End Sub
******************************************************************************************************
Date calculation (difference between 2 dates)
******************************************************************************************************
Public Function PaymentOverdue(datDateInvoiced As Date, datDatePaid As Date) As String
'
' Purpose: Demonstrate date handling
' Arguments: none
' Returns: none
'
' DateDiff calculates the difference between two dates
' The "d" says return the number of days difference
If DateDiff("d", datDateInvoiced, datDatePaid) > 30 Then
PaymentOverdue = "Overdue"
Else
PaymentOverdue = "OK"
End If
End Function
******************************************************************************************************
Compaction (automating for the User -- every 5 times used)
******************************************************************************************************
Option Compare Database
Option Explicit
Public booCompactTime As Boolean
Function Autoexec()
'***************************************************************************
'Purpose:
'Comments: 1. Compiles all code in the database if it is uncompiled
' 2. Writes usage info to custom database properties
' 3. Writes usage info to the Registry
' 4. Sets flag to indicate if db is due for compacting
'***************************************************************************
Set db = CurrentDb
'Find out how many times this particular database has been opened
IncrementTimesOpened
lngDBTimesOpened = db.Properties("TimesOpened")
'If this is the first time for this database, then show the greeting form
If lngDBTimesOpened = 1 Then
DoCmd.OpenForm "frmGreeting", , , , , acDialog
Else
'Else open the greeting form unless the user has deselected the re-view check box
If GetSetting("MWSDB", "Preferences", "StartUpDialog", True) Then
DoCmd.OpenForm "frmGreeting", , , , , acDialog
End If
End If
Autoexec_Exit:
Exit Function
Autoexec_Err:
'Turn screen updating back on
Application.Echo True
End Function
strMsg = "The following error occurred in the " & strProcName & " procedure"
strMsg = strMsg & Chr$(10) & Chr$(10)
strMsg = strMsg & "Error Number: " & Format$(intErr) & Chr$(10)
strMsg = strMsg & "Error Description: " & Error$
GlobalErr_Exit:
Exit Sub
End Sub
Sub MarkCompileTime()
'***************************************************************************
'Purpose: To set a db property indicating when the database was last
' programmatically compiled
'Parameters: None
'Returns: Nothing
'***************************************************************************
CurrentDb.Properties("LastCompiled") = Now
MarkCompileTime_Exit:
Exit Sub
MarkCompileTime_Err:
Select Case Err.Number
Case 3270 'Error code for "Property not found"
Set pty = CurrentDb.CreateProperty("LastCompiled", dbDate, Now())
CurrentDb.Properties.Append pty
Resume
Case Else
Call GlobalErr("MarkCompileTime", Err.Number)
Resume MarkCompileTime_Exit
Resume
End Select
End Sub
Sub IncrementTimesOpened()
'***************************************************************************
'Purpose: To set a db property indicating the number of times the
' database has been opened
'Parameters: None
'Returns: Nothing
'***************************************************************************
lngDBTimesOpened = CurrentDb.Properties("TimesOpened")
CurrentDb.Properties("TimesOpened") = lngDBTimesOpened + 1
'Warn the user to re-compact every five opens
If lngDBTimesOpened Mod 5 = 0 Then
booCompactTime = True
End If
IncrementTimesOpened_Exit:
Exit Sub
IncrementTimesOpened_Err:
Select Case Err.Number
Case 3270 'Error code for "Property not found"
Set pty = CurrentDb.CreateProperty("TimesOpened", dbDate, 0)
CurrentDb.Properties.Append pty
Resume
Case Else
Call GlobalErr("IncrementTimesOpened", Err.Number)
Resume IncrementTimesOpened_Exit
Resume
End Select
End Sub
******************************************************************************************************
Excel chart creation thru automation
******************************************************************************************************
Private Sub cmdCreateSpreadsheet_Click()
Dim varArray as Variant
Dim recSales As Recordset ' Recorset to create chart from
Dim objExcel As New Excel.Application ' Excel object
DoCmd.Hourglass True ' Turn on the Hourglass -- to encourage wait by User
Set recSales = CurrentDb().OpenRecordset("qryMonthlySales") ' Creating recordset from QueryDef
recSales.MoveLast ' Move to the last record to update record count
recSales.MoveFirst ' Move to the first record
varArray = recSales.GetRows(recSales.RecordCount) ' Load the array with the query results
recSales.Close ' Close the recordset
objExcel.Workbooks.Add ' Add a new Excel workbook
' ****************************************************************************
For intFld = 0 To UBound(varArray, 1) ' Pass the values from the array into the Excel sheet
For intRow = 0 To UBound(varArray, 2)
objExcel.Cells(intRow + 2, intFld + 1).Value = varArray(intFld, intRow)
Next
Next
' *****************************************************************************
' Work on the data as desired using regular Excel commands -- simply recede them with
' objExcel as with objExcel.Range("A1:C3").Select
' *****************************************************************************
' As with modifying a Chart -- see this:
Set objChart = objExcel.ActiveChart
With objChart
.ChartType = xl3DArea
.HasTitle = True ' Add some titles
.ChartTitle.Text = "Monthly Sales"
.Axes(xlCategory).HasTitle = True
.Axes(xlCategory).AxisTitle.Caption = "Month"
.Axes(xlValue).HasTitle = True
.Axes(xlValue).AxisTitle.Caption = "Sales"
.Axes(xlSeriesAxis).HasTitle = True
.Axes(xlSeriesAxis).AxisTitle.Caption = "Year"
.HasLegend = False
End With
objExcel.ActiveWorkbook.Close True, "C:\BegVBA\MnthSale.XLS" ' Saving & closing Workbook
' Close Excel and free the memory
Set objChart = Nothing
Set objExcel = Nothing
DoCmd.Hourglass False
objExcel.Quit ' Leave the Excel application
Exit Sub
*** or a more complext example of inserting data and creating a chart therefrom ******
Public Sub CreateChart()
'
' Purpose: To create an Excel chart from a recordset
'
Dim recSales As Recordset ' Recorset to create chart from
Dim varArray As Variant ' Array of entries from above
Dim objExcel As New Excel.Application ' Excel object
Dim objChart As Object ' Excel chart object
Dim intFields As Integer ' Number of fields in recordset
Dim intRows As Integer ' Number of rows in recordset
Dim intFld As Integer ' Loop index for fields
Dim intRow As Integer ' Loop index for rows
Dim strRange As String ' Range of Excel cells for data
' Copy the whole recordset into an array, and close the recordset
recSales.MoveFirst
varArray = recSales.GetRows(recSales.RecordCount)
' Pass the values from the array into the Excel sheet
For intFld = 0 To intFields
For intRow = 0 To intRows
objExcel.Cells(intRow + 2, intFld + 1).Value = varArray(intFld, intRow)
Next
Next
' Determine the A1:C2-type reference for the range containing our data
strRange = "A1:" & Chr$(Asc("A") + intFields) & Format$(intRows + 2)
' Select the range in the Excel sheet and make it active
objExcel.Range(strRange).Select
objExcel.Range(Mid(strRange, 4)).Activate
CreateChart_Exit:
Exit Sub
CreateChart_Err:
' Tidy up - ensure all objects are cleared
Set objChart = Nothing
objExcel.ActiveWorkbook.Close False
objExcel.Quit
Set objExcel = Nothing
DoCmd.Hourglass False
MsgBox Err.Number & " - " & Err.Description
Resume CreateChart_Exit
End Sub
******************************************************************************************************
Security (show "no delete" permissions)
******************************************************************************************************
Sub ShowNoDelPerms()
Next
Next
Debug.Print "Done"
End Sub
******************************************************************************************************
Security (listing permissions)
******************************************************************************************************
Sub ShowPerms()
Next
Next
Debug.Print "Done"
End Sub
******************************************************************************************************
Security (adding User to Group)
******************************************************************************************************
Sub AddUserToGroup()
wks.Groups("Registrars").Users.Append usrMark
End Sub
**** Alternative example **************
Set ws = DBEngine.Workspaces(0)
With newUsr.Groups
.Append ws.CreateGroup("Users")
.Append ws.CreateGroup("Managers")
.Refresh
End With
End Sub
******************************************************************************************************
Security (adding a Group Account)
******************************************************************************************************
Sub GroupAdd()
Dim wks As Workspace
Dim grpRegistrars As Group
Dim strGroupPID As String
End Sub
******** Alternative example ***********
Set ws = DBEngine.Workspaces(0)
End Sub
******************************************************************************************************
Record locking types and method
******************************************************************************************************
NOTE: We're passing the subroutine below the description of the type of locking desired
Sub SetAndGetLocking(strLockType As String)
End Sub
******************************************************************************************************
Progress meter in status bar
******************************************************************************************************
Sub ShowProgress()
'
' Purpose: To display a progress bar in the status bar
'
For i = 0 To 300
'Perform some processing or other...
For j = 0 To 1000
intRnd = Rnd * 10 + 1
Next j
Next i
End Sub
******************************************************************************************************
Error Table Creation
******************************************************************************************************
Function AccessAndJetErrorsTable() As Boolean
'
' Purpose: Create a table and populate it with Access errors
'
dbC.TableDefs.Append tblErr
AccessAndJetErrorsTable = True
AccessAndJetErrorsTable_Exit:
Exit Function
AccessAndJetErrorsTable_Err:
MsgBox Err & ": " & Err.Description
AccessAndJetErrorsTable = False
Resume AccessAndJetErrorsTable_Exit
End Function
******************************************************************************************************
Field (listing single col wi Recordset)
******************************************************************************************************
Public Sub ErrorHelp(strColumn As String)
'
' Purpose: Demonstrate a naff error message, but useful help
' when searching a recordset for a column
' Arguments: strColumn The column to search for
'
End Sub
******************************************************************************************************
Records Found With SQL into Array
******************************************************************************************************
Private Sub GetWhiskies(strRegion As String, Optional bolPrice As Boolean)
'
' Purpose: To show the whiskies for a region
'
recR.Close
End Sub
******** To display the array we just created use ****************
End Sub
******************************************************************************************************
Properties of a Database (determining)
******************************************************************************************************
Sub EnumDBProperties()
'
' Purpose: Enumerate the database properties
'
Dim pty As Property
On Error Resume Next
For Each pty In CurrentDb.Properties
Debug.Print pty.Name & ": " & pty.Value
Next
End Sub
******** Sample output shown below ** Note the Property name is shown preceding the quote *** highlighted important ones
Name: C:\TEMP\WHISKY2000.MDB
Connect:
Transactions: True
Updatable: True
CollatingOrder: 1033
QueryTimeout: 60
Version: 4.0
RecordsAffected: 0
ReplicaID:
DesignMasterID:
AccessVersion: 08.50
Build: 3822
AllowBypassKey: True
Show Values Limit: 1000
Show Values in Indexed: 1
Show Values in Non-Indexed: 1
Show Values in Remote: 0
AppTitle: The Malt Whisky Store
StartUpShowDBWindow: True
StartUpShowStatusBar: True
AllowShortcutMenus: True
AllowFullMenus: True
AllowBuiltInToolbars: True
AllowToolbarChanges: True
AllowBreakIntoCode: True
AllowSpecialKeys: True
LastCompiled: 8/19/1997 9:05:04 AM
TimesOpened: 1/23/1900
Track Name AutoCorrect Info: 0
Perform Name AutoCorrect: 0
CpgConversion: 1252
******************************************************************************************************
Recordset (Rows & Fields) into Array
******************************************************************************************************
Sub TestGetRows()
'
' Purpose: Demonstrate the use of the GetRows function to read
' values from a recordset into an array
Dim varValues As Variant
Dim rs As Recordset
Dim varRow As Variant
Dim intRowCount As Integer
Dim intFieldCount As Integer
Dim i As Integer
Dim j As Integer
Set rs = CurrentDb().OpenRecordset("Order")
varValues = rs.GetRows(2)
rs.Close
intFieldCount = UBound(varValues, 1)
intRowCount = UBound(varValues, 2)
For j = 0 To intRowCount
For i = 0 To intFieldCount
Debug.Print "Row " & j & ", Field " & i & ": ";
Debug.Print varValues(i, j)
Next
Next
End Sub
******************************************************************************************************
DLookup() function -- pulling data from a table or query
******************************************************************************************************
Using the DLookup() function you can display data obtained directly from a table or query. You can use the DLookup() function as
follows:
In a query In a calculated field expression in a Field cell, to specify criteria in a Criteria cell, or in an expression in the Update
To cell in an update query.
In a VBA procedure In a condition or method argument.
In a form or report In a calculated control.
The DLookup() function takes 3 arguments: DLookup("fieldname", "tablename" or "queryname", "searchcondition")
Note: All three arguments must be expressed as strings.
Syntax for search condition is:
fieldname = Forms!formname!controlname
Where the left side of the search condition is the name of the field in the table or query you're searching and the right side is the fully
qualified reference to the form control with the value you're searching for.
Example:
=DLookup("Description", "Categories", "CategoryID = Forms!Products!CategoryID")
******************************************************************************************************
ControlSource data from Another Form
******************************************************************************************************
You can pull data into an unbound control from controls on another open form or from fields in another form's data source by setting the
control's ControlSource property to an expression (fully-qualified) that refers to these controls or fields.
Example: An unbound control on the Orders form obtaining data from the Employees form:
=Forms!Employees!LastName & ", " & Forms!Employees!FirstName
=Forms![Customer Orders]!CustomerID ' Displays the value of the CustomerID field in the data source of the Customer Orders form.
=Forms![Customer Orders]![Customer Orders Subform1]!OrderDate
' Displays the value of the OrderDate control of the current record in the Customer Orders
Subform1 subform of the Customer Orders form.
=[Orders Subform]!UnitPrice ' Displays the value fo the UnitPrice control of the current record in the Orders Subform of the
active form. The calculated control is located on the main form.
=Parent!OrderID ' Displays the value of the OrderID control on the parent form of the current subform. The
calculated control is located on the subform.
*** Can also set the control source referring to two separate open forms in an expression **
="The Customers current record is " & Screen.ActiveForm.CurrentRecord & " and the Employees current record is " & Forms!
Employees.CurrentRecord
******************************************************************************************************
Calculated Controls (some ControlSource expressions) -- get data from same form
******************************************************************************************************
=FirstName & " " & LastName ' Displays the values in the FirstName and LastName controls separated by a space
=Left(CompanyName, 4) ' Displays the first four characters of the value of the CompanyName control.
=Sum(Quantity*Price) ' Displays the sum of the product of the values of the Quantity and Price fields for all the records
displayed on the form.
=IIf(IsNull(Sum(Quantity*Price),0,Sum(Quantity*Price))
' Displays a zero if the sum is Null; otherwise, displays the sum.
=Count(EmployeeID) ' Displays the number of records displayed by the form that have a non-Null value in the EmployeeID
field.
=Count(*) ' Displays the number of records displayed by the form. Use the asterisk(*) to count all of the records.
NOTE: If you are working interactively, you can force the update of calculated controls by pressing F9. Otherwise, you can write a
program to do so keyed to some event (Exit, LostFocus, GotFocus, etc.)
******************************************************************************************************
Variables & Procedures (declarations, scope, passing info examples)
******************************************************************************************************
Option Compare Database
Option Explicit
Private strPrivate As String
Public gstrPublic As String
Public strModule As String
Public Sub LocalVariable()
Dim strLocal As String
strLocal = "'Local variable in LocalVariable procedure'"
MsgBox strLocal
Call GetLocal(strLocal) ' See below
End Sub
Public Sub GetLocal(strA As String)
MsgBox strA & " passed as an argument to GetLocal"
End Sub
Exit_OutputToHTML_Click:
Exit Sub
Err_OuputToHTML_Click:
' If action was cancelled by the user, don't display an error message.
Const conErrDoCmdCancelled = 2501
If (Err = conErrDoCmdCancelled) Then
Resume Exit_OutputToHTML_Click
Else
MsgBox Err.Description
Resume Exit_OutputToHTML_Click
End If
End Sub
******************************************************************************************************
Creating a new database
******************************************************************************************************
Private Sub cmdNewCatalog_Click()
Dim newdb As ADOX.Catalog
Set newdb = New ADOX.Catalog
newdb.Create "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\VBAHandbook\MyNewDB.mdb"
End Sub
******************************************************************************************************
Focus (giving a control focus)
******************************************************************************************************
' Give ProductName control focus.
Forms![Products]!ProductName.SetFocus
******************************************************************************************************
Closing a form
******************************************************************************************************
' Close Product List form.
DoCmd.Close acForm, "Product List"
' Close form (simpler form -- when inside the form)
DoCmd.Close
******************************************************************************************************
Opening form (in data entry mode)
******************************************************************************************************
' Open Products form in data entry mode and store SupplierID in the form's OpenArgs property.
DoCmd.OpenForm strDocName, , , , acAdd, , Me!SupplierID
' Open form (simply to view data)
DoCmd.OpenForm strDocName, , , , , acDialog
******************************************************************************************************
Printing Reports example
******************************************************************************************************
Sub PrintReports(PrintMode As Integer)
On Error GoTo Err_Preview_Click
' This procedure used in Preview_Click and Print_Click Sub procedures.
' Preview or print report selected in the ReportToPrint option group.
' Then close the Print Sales Reports Dialog form.
Dim strWhereCategory As String
strWhereCategory = "CategoryName = Forms![Sales Reports Dialog]!SelectCategory"
Select Case Me!ReportToPrint
Case 1
DoCmd.OpenReport "Employee Sales by Country", PrintMode
Case 2
DoCmd.OpenReport "Sales Totals by Amount", PrintMode
Case 3
If IsNull(Forms![Sales Reports Dialog]!SelectCategory) Then
DoCmd.OpenReport "Sales by Category", PrintMode
Else
DoCmd.OpenReport "Sales by Category", PrintMode, , strWhereCategory
End If
End Select
DoCmd.Close acForm, "Sales Reports Dialog"
Exit_Preview_Click:
Exit Sub
Err_Preview_Click:
Resume Exit_Preview_Click
End Sub
******************************************************************************************************
File Open dialog (for choosing file) -- example
******************************************************************************************************
Sub getFileName()
' Displays the Office File Open dialog to choose a file name
' for the current employee record. If the user selects a file
' display it in the image control.
Dim fileName As String
Dim result As Integer
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "Select Employee Picture"
.Filters.Add "All Files", "*.*"
.Filters.Add "JPEGs", "*.jpg"
.Filters.Add "Bitmaps", "*.bmp"
.FilterIndex = 3
.AllowMultiSelect = False
.InitialFileName = CurrentProject.path
result = .Show
If (result <> 0) Then
fileName = Trim(.SelectedItems.Item(1))
Me![ImagePath].Visible = True
Me![ImagePath].SetFocus
Me![ImagePath].Text = fileName
Me![FirstName].SetFocus
Me![ImagePath].Visible = False
End If
End With
End Sub
******************************************************************************************************
Opening & Closing a Form
******************************************************************************************************
Private Sub OpenChildForm()
DoCmd.OpenForm "OrdersLinked"
If Not Me.[ToggleLink] Then Me![ToggleLink] = True ' See the ToggleLink routine below
End Sub
Sub ToggleLink_Click()
On Error GoTo ToggleLink_Click_Err
If ChildFormIsOpen() Then
CloseChildForm
Else
OpenChildForm
FilterChildForm
End If
ToggleLink_Click_Exit:
Exit Sub
ToggleLink_Click_Err:
MsgBox Error$
Resume ToggleLink_Click_Exit
End Sub
******************************************************************************************************
Form Open? (True or False)
******************************************************************************************************
Private Function ChildFormIsOpen()
ChildFormIsOpen = (SysCmd(acSysCmdGetObjectState, acForm, "OrdersLinked") And acObjStateOpen) <> False
End Function
******************************************************************************************************
Me object
******************************************************************************************************
In procedures stored in a form (or report) module use the "Me" property to refer to the form or report itself.
From within the form you could execute the statement:
Me.Caption = "My Favorite Form" (the caption property of the form would be changed, temporarily, to "My Favorite Form")
Also you can get the form's RecordSource property and store it in the strDataSource variable using this statement:
strDataSource = Me.RecordSource
You can update the form's data source by calling its Requery method as follows:
Me.Requery
NOTE: You can't use test statements that include Me object in the immediate window only in a procedure stored in a form or a
report module.
ALSO: The Me object is preferable to the ActiveForm or ActiveReport property, since you have no doubt as to what Me refers to;
whereas, one cannot always count on a form or report being the "Active" object of it's type.
******************************************************************************************************
Bookmarks
******************************************************************************************************
To track records in a recordset, Access creates bookmarks. A bookmark is a unique binary string (you cannot read it or alter it in any way;
it's also not the same as the record number) that Access creates for each record in a form's recordset each time you open a form.
The value of the form's bookmark property is the value of the bookmark of the current record. You can:
a) Store the bookmark in a string variable.
b) Return to the bookmark by setting the form's bookmark property to the previously stored variable.
strMark = Forms!Customers.Bookmark (stores the current record bookmark in the string "strMark")
Forms!Customers.Bookmark = strMark (to return to the previously stored bookmark)
NOTE: Bookmarks are the fastest way to return to a record. Bookmarks are not saved with the records; when you close the form
the recordset and associated bookmarks cease to exist.
NOTE: While each recordset has it's own set of bookmarks each time the recordset is created a clone will have the same
bookmarks as the recordset from which the clone is derived; therefore, a bookmark obtained from the clone can be used to access the
recordset.
strMark = Forms!Customers.RecordsetClone.Bookmark (stores the bookmark from the current record of clone)
Forms!Customers.Bookmark = strMark (goes to that record in the recordset)
******************************************************************************************************
Clones
******************************************************************************************************
You can create a Recordsetclone object (basically a copy of the Recordset in memory which can be manipulated separately from the
primary Recordset) for the Customers form using the syntax:
Set clone = Forms!Customers.RecordsetClone
You can navigate independently in the Recordset and the Recordsetclone objects each without affecting the other.
NOTE: Some properties and methods are available in one and not the other.
******************************************************************************************************
Variables
******************************************************************************************************
When a property setting refers to an object, you can assign the object to a variable by using a statement similar to:
Set frm = Screen.ActiveForm
******************************************************************************************************
Data-Conversion functions (i.e., converts string or numeric expression)
******************************************************************************************************
CBool Boolean. If expression is zero, False is returned; otherwise, True is returned.
CByte Byte
CCur Currency
CDate Date
CDbl Double
CDec Decimal
CInt Integer
CLng Long
CSng Single
CStr String
CVar Variant
CVDate Variant of subtype Date
CVErr Variant of subtype Error
Fix Returns the integer portion of a number; rounds negative numbers up.
Hex Variant (hexadecimal)
Int Returns the integer portion of a number; rounds negative numbers down.
Oct Variant (octal)
Str Variant (string)
Val Converts a string of number characters into a number of appropriate type.
******************************************************************************************************
Control Source properties (Access)
******************************************************************************************************
As an alternative to using a calculated query field, you can use a calculated form control. A calculated control is a control that displays the
result of an expression. You enter the expression preceded by an equal sign (=) in the control's ControlSource property.
Examples:
=FirstName & " " & LastName (Displays the values in the FirstName and LastName controls separated by a space).
=Left(CompanyName, 4) (Displays the first four characters of the value of the CompanyName control).
=Sum(Quantity*Price) (Displays the sum of the product of Quantity and Price fields for all the records displayed by the form).
=IIf(IsNull(Sum(Quantity*Price),0,Sum(Quantity*Price))
(Displays a zero if the sum is Null; otherwise, displays the sum the IIf function is an in-line if-then-
else).
=Count(EmployeeID) (Displays the number of records displayed by the form that have a non-Null value in the EmployeeID
field).
*** Can also refer to another open form ***
=Forms![Customer Orders]!CustomerID
(Displays the value of the CustomerID field in the data source of the Customer Orders form).
=Forms![Customer Orders]![Customer Orders Subform1]!OrderDate
(Displays the value of the OrderDate control of the current record in the Customer Orders Subform1
subform of the Customer Orders form).
=[Orders Subform]!UnitPrice (Displays the value of the UnitPrice control of the current record in the Orders Subform of the active
form. The calculated control is located on the main form).
=Parent!OrderID (Displays the value of the OrderID control on the parent form of the current subform. The calculated
control is located on the subform).
="The Customers current record is " & Screen.ActiveForm.CurrentRecord & " and the Employees current record is " & Forms!
Employees.CurrentRecord
(Displays the current record numbers of the two open forms)
You can use any of the domain aggregate functions (shown below) in the ControlSource expression. All of them use the same syntax. [Note:
The third argument (i.e., setting up a restricted domain with a search condition) is optional; if you don't specify a search condition, the
function uses the larger set of records (the domain). If no record satisfies the search condition, or if the domain contains no records, the
domain aggregate function returns a Null.
******************************************************************************************************
SQL Statement (Full Syntax with explanation -- click on the Hyperlinks below to go to appropriate subheading)
******************************************************************************************************
SELECT [ALL | DISTINCT] select_list (the fields or columns which we're looking for)
FROM table/view_list (the tables we're selecting from or virtual tables creating by using Joins of various types)
[WHERE search_conditions] (optional criteria specifying what records or rows we which to select)
[GROUP BY group_by_list] (optional grouping criteria need for summary totals at whatever levels)
[HAVING search_conditions] (optional WHERE clause for groups just as WHERE limits rows, HAVING limits groups)
[ORDER BY order_by_list] (optional sort specification)
The DISTINCT and ALL keywords in the SELECT list let you specify what to do with duplicate rows in your results. ALL returns all
qualified rows and is the default. DISTINCT returns only unique rows.
Example:
SELECT DISTINCT lastname, firstname, ssn
** More Select Examples (also with LIKE for limited pattern-matching) *****
The LIKE pattern matching operator can also be used in the conditional selection of the where clause. Like is a very powerful operator that
allows you to select only rows that are "like" what you specify. The percent sign "%" can be used as a wild card to match any possible
character that might appear before or after the characters specified. For example:
SELECT first, last, city FROM empinfo WHERE first LIKE 'Er%';
This SQL statement will match any first names that start with 'Er'. Strings must be in
single quotes.
SELECT first, last FROM empinfo WHERE last LIKE '%s';
This statement will match any last names that end in a 's'.
SELECT * FROM empinfo WHERE first = 'Eric';
This will only select rows where the first name equals 'Eric' exactly.
SELECT first, last, city FROM empinfo;
SELECT last, city, age FROM empinfo WHERE age > 30;
SELECT first, last, city, state FROM empinfo WHERE first LIKE 'J%';
SELECT * FROM empinfo;
SELECT first, last, FROM empinfo WHERE last LIKE '%s';
SELECT first, last, age FROM empinfo WHERE last LIKE '%illia%';
SELECT * FROM empinfo WHERE first = 'Eric';
SELECT name
FROM actor, casting
WHERE casting.movieid='1' and casting.actorid = actor.id ' joining two tables together
SELECT title, name
FROM actor, casting, movie
WHERE movie.title = 'Aliens' and movie.id = casting.movieid and
casting.actorid = actor.id ' joining three tables together!!
' Can JOIN multiple SELECT statements by using UNION command to send data to a single field (as with Publishability Review!)
Select emp_lname as "Last Name", emp_fname as "First Name", DBA.employee.dept_id as "Dept. #", dept_name as "Department"
FROM DBA.employee, DBA.department
WHERE DBA.employee.dept_id = DBA.department.dept_id (joining two tables to create a relationship between them)
ORDER BY emp_lname
Note: In the above select example lastname & firstname came from the DBA.employee table while the department name came from the
DBA.department table -- the two tables were joined on dept_id field to create a relationship.
Also Note: Since both table contained the same field (dept_id) when I selected columns in the above example, I had to qualify the dept_id
field with the table name to show which one I was after even though they were both the same.
FROM tblEmployees Emp (gives the tblEmployees the alias of "Emp" which can be used thereafter)
WHERE advance * 2 > ytd_sales * price (can use arithmetic & comparison operations +, -, *, /, =, <, >, <>, !=, <=, >=, and so on)
WHERE advance < 5000 or ytd_sales > 2000 (combinations or logical negations of conditions (AND, OR, NOT)
WHERE lastname > 'McBadden' (whose last names follow McBadden in the alphabet; note -- depends on character-sorting sequence of
DBMS)
WHERE ytd_sales between 4095 and 12000 (between or not between can also be used -- the upper and lower values of 12000 and 4095 are
considered valid)
WHERE state in ('CA', 'IN', 'MD') (in or not in a specified list) this is equivalent to
WHERE state = 'CA' or state = 'IN' or state = 'MD'
the requirements are:
inside parentheses
separated by commas
enclosed in quotes, if they are character or date values
NOTE: Also important use of IN keyword is in nested queries, referred to as subqueries.
WHERE phone NOT LIKE '415%' (character matches like or not like as with limited pattern-matching: the percent % stands for zero or
more characters and the underscore _ stands for any single character. You use the ESCAPE keyword when your pattern includes one of these
wildcard characters to be treated literally).
WHERE notes like '%@%%' escape '@' (here we're looking for a literal percent in the middle of a string and we're designating the @
character as the escape character. So we have wildcards on both ends and one escaped percent in the middle.)
WHERE state IS NOT NULL (to avoid selecting records with no value in this particular row though we're naming the column)
NOTE: Searching for NULLs is a good check on the data-integrity of the database!
SELECT msp.name, msp.party ' This query locates any name in the msp table in which the party field is NULL (nothing entered)
FROM msp
WHERE msp.party IS NULL
SELECT lname as "Customer", SUM(amount) as "Total Cost" ' Customer last name is coming from DBA.customer table
FROM DBA.sales_order, DBA.fin_data, DBA.customer ' Amount is coming from DBA.fin_data table
WHERE DBA.sales_order.fin_code_id = DBA.fin_data.code ' cust_id is coming from the DBA.sales.order
AND DBA.sales_order.cust_id = DBA.customer.id
GROUP BY lname, cust_id
ORDER by lname
SELECT yr, COUNT(yr) ' Just need to make sure that we're summarizing in the Selection the same as we
FROM movie, actor, casting ' are seeking to GROUP BY
WHERE actor.name = 'John Travolta' and
actor.id = casting.actorid and
casting.movieid = movie.id
GROUP BY yr
SELECT COUNT(name), name ' We're counting the number of times actors have had the starring role
FROM actor, casting
WHERE casting.ord = '1' and
casting.actorid = actor.id
GROUP BY name
HAVING COUNT(name) >= 10 ' We're restricting our groups to those containing counts greater than or equal to 10
ORDER BY name
SELECT Count(actorid), title ' We're counting the cast list for films in 1978
FROM movie, casting
WHERE yr = '1978' and
movie.id = casting.movieid
GROUP BY title ' The Count and Group By commands work in conjunction -- each dependent on other
ORDER BY Count(actorid) DESC ' Sorting the list in descending order
ORDER BY price, pub_id (like the SELECT list, the ORDER BY list can have one element or multiple elements if there are multiple
elements they're separated by commas you can have as many sort levels as you like)
The ORDER BY list can include four kinds of expressions, ranging from simple to complex:
A column name (such as lastname, pub_id, etc.)
A column name and arithmetic operators or functions (price * 1.0825)
A display label assigned to a column or expression in the SELECT clause such as "Income"
A position number (the number of this column or expression in the SELECT list in the example below, price is the fourth entry in
the SELECT list)
ORDER BY 4
NOTE: Position numbers work just like column names in ORDER BY. You can:
Use position numbers to represent simple columns as well as more complex expressions.
Freely mix position numbers and columns or expressions.
Specify a direction with ASC or DESC for position numbers just as with column names.
You can specify an ascending (the default) or descending sort by including the keywords ASC or DESC immediately after the sort item.
Example:
ORDER BY price DESC, pub_id DESC
Concerning the sorting of NULLs Not all systems order nulls the same way. They should be either greater than or less than all non-null
values. Which you get depends on your DBMS implementation.
******************************************************************************************************
SQL Commands to Create a Table
******************************************************************************************************
The create table statement is used to create a new table. Here is the format of a simple create table statement:
create table "tablename" ("column1" "data type", "column2" "data type", "column3" "data type");
create table "tablename" ("column1" "data type" [constraint], "column2" "data type" [constraint], "column3" "data type" [constraint]);
[ ] = optional
Note: You may have as many columns as you'd like, and the constraints are optional. Example:
create table employee (first varchar(15), last varchar(20), age number(3), address varchar(30), city varchar(20), state varchar(20));
To create a new table, enter the keywords create table followed by the table name, followed by an open parenthesis, followed by the first
column name, followed by the data type for that column, followed by any optional constraints, and followed by a closing parenthesis. It is
important to make sure you use an open parenthesis before the beginning table, and a closing parenthesis after the end of the last column
definition. Make sure you seperate each column definition with a comma. All SQL statements should end with a ";".
The table and column names must start with a letter and can be followed by letters, numbers, or underscores - not to exceed a total of 30
characters in length. Do not use any SQL reserved keywords as names for tables or column names (such as "select", "create", "insert", etc).
Data types specify what the type of data can be for that particular column. If a column called "Last_Name", is to be used to hold names, then
that particular column should have a "varchar" (variable-length character) data type.
Creating and filling a table with data from a 2nd table in a single SQL statement !!
NOTE: Everything below can be run in a single SQL Statement!
Create table NewPubReview
(editor numeric(8) not null,
units numeric(8) not null,
hours numeric(8) not null)
Insert into NewPubReview
Select editor1_id as editor, units1 as units, hours1 as hours
FROM PubReview
WHERE editor1_id = '250503'
Insert into NewPubReview ' Then appending some more data -- into same columns with a different query
Select editor2_id as editor, units2 as units, hours2 as hours
FROM PubReview
WHERE editor2_id = '250503'
Example:
insert into employee (first, last, age, address, city, state) values ('Luke', 'Duke', 45, '2130 Boars Nest', 'Hazard Co', 'Georgia');
To insert records into a table, enter the key words insert into followed by the table name, followed by an open parenthesis, followed by a list
of column names separated by commas, followed by a closing parenthesis, followed by the keyword values, followed by the list of values
enclosed in parenthesis. The values that you enter will be held in the rows and they will match up with the column names that you specify.
Strings should be enclosed in single quotes, and numbers should not.
In the example above, the column name first will match up with the value 'Luke', and the column name state will match up with the value
'Georgia'.
******************************************************************************************************
SQL commands to change table data
******************************************************************************************************
The update statement is used to update or change records that match a specified criteria. This is accomplished by carefully constructing a
where clause. The SET statement is the new data and the where statement is the old data.
UPDATE "tablename"
SET "columnname" = "newvalue"[,"nextcolumn" = "newvalue2"...]
WHERE "columnname" OPERATOR "value" [and|or "column" OPERATOR "value"];
[] = optional
Example of completely changing the value in a field -- where entire field is a certain character string:
UPDATE DBA.sales_order
SET fin_code_id = 'r2'
WHERE fin_code_id = 'r1'
Example of partially changing the first four characters of a field -- and leaving the remainder of the field the same. Use in
conjunction with SUBSTR( expression, start, length) expression.
Let's say we want to change the year portion from 1993 to 1992 of the field order_date:
1993-01-02
1993-01-04
1993-01-06
Firstpart = SUBSTR(order_date, 1, 4)
Secondpart = SUBSTR(order_date, 5) ' The length is optional -- will simply take the rest of the expression (very nice!)
More Examples (note: in examples below we can be looking at other fields in same table -- or even other tables!:
UPDATE phone_book
SET area_code = 623
WHERE prefix = 979;
UPDATE phone_book
SET last_name = 'Smith', prefix=555, suffix=9292
WHERE last_name = 'Jones';
UPDATE employee
SET age = age+1
WHERE first_name='Mary' and last_name='Williams';
******************************************************************************************************
SQL commands to delete rows from table
******************************************************************************************************
The delete statement is used to delete records or rows from the table.
DELETE FROM "tablename" WHERE "columnname" OPERATOR "value" [and|or "column" OPERATOR "value"];
[ ] = optional
Examples:
Note: if you leave off the where clause, all records will be deleted!
To delete an entire record/row from a table, enter "delete from" followed by the table name, followed by the where clause which contains the
conditions to delete. If you leave off the where clause, all records will be deleted!!
******************************************************************************************************
SQL command to delete a table
******************************************************************************************************
The drop table command is used to delete a table and all rows in the table.
Example:
To delete an entire table including all of its rows, issue the drop table command followed by the tablename. drop table is different from
deleting all of the records in the table. Deleting all of the records in the table leaves the table including column and constraint information.
Dropping the table removes the table definition as well as all of its rows.
******************************************************************************************************
Show/Hide Controls
******************************************************************************************************
lblNames.Visible = True
lstNames.Visible = True
******************************************************************************************************
Userform_Initialize equivalent
******************************************************************************************************
Private Sub Form_Load()
'Set global variable gintResubmitManuscript to be = 0.
gintResubmitManuscript = 0
...
End Sub
******************************************************************************************************
Form Activation
******************************************************************************************************
stDocName = "frmAssignments"
DoCmd.OpenForm stDocName, , , stLinkCriteria
******************************************************************************************************
Combobox Update and Item Selection
******************************************************************************************************
Private Sub cboPubName_Change()
'Reset row source of project number combo box:
With cboProjNum
.SetFocus
.Text = ""
.Requery
.ListIndex = 0 ' Selects the first item to display
End With
End Sub
******************************************************************************************************
Combobox Load with SQL Query
******************************************************************************************************
Private Sub cboPubName_AfterUpdate()
Dim strSQL As String
mstrPubName = cboPubName.Text
'Develop SQL statement for row source of Project Number combo box:
strSQL = "SELECT DISTINCTROW [tblAssignment].[ProjectNumber] FROM tblAssignment WHERE " & _
"[tblAssignment].[PubName] = '" & mstrPubName & "';"
End Sub
******************************************************************************************************
View Creation (SQL)
******************************************************************************************************
CREATE VIEW ORDERS_BY_STATE
(CLIENT_NAME, STATE, ORDER_NUMBER)
AS SELECT CLIENT.CLIENT_NAME, STATE, ORDER_NUMBER FROM CLIENT, ORDERS
WHERE CLIENT.CLIENT_NAME = ORDERS.CLIENT_NAME;
Note: The above view has three columns: CLIENT_NAME, STATE, and ORDER_NUMBER. CLIENT_NAME appears in both the
CLIENT and the ORDERS table and serves as the link between the two tables. The new view draws the STATE information from the
CLIENT table and takes the ORDER_NUMBER of each order from the ORDERS table.
Note: Could add other conditions (using the AND logical connector) in the WHERE clause.
******************************************************************************************************
Field (i.e., Column) Constraints
******************************************************************************************************
CREATE TABLE TESTS (
TEST_NAME CHARACTER (30) NOT NULL,
STANDARD_CHARGE NUMERIC (6,2)
CHECK (STANDARD_CHARGE >= 0.0 AND STANDARD_CHARGE <= 200.0)
);
Note: UNIQUE is another constraint you can apply to a column, as well as PRIMARY KEY.
******************************************************************************************************
Table Creation (with SQL)
******************************************************************************************************
CREATE TABLE ORDERS (
ORDER_NUMBER INTEGER NOT NULL,
CLIENT_NAME CHARACTER (30),
TEST_ORDERED CHARACTER (30),
SALESPERSON CHARACTER (30),
ORDER_DATE DATE
);
******************************************************************************************************
Recordset (Working With)
******************************************************************************************************
rsCustomer.MoveNext ' Moves the record pointer to the next record causes an error if there isn't a next record (i.e., you're at the last
record or there aren't any records)
rsCustomer.MovePrevious ' Moves to the previous record causes an error if there isn't a previous record (you are at the very first record
or there aren't any records)
rsCustomer.MoveFirst ' Moves to the very first record in the recordset causes an error only if there aren't any records.
rsCustomer.MoveLast ' Moves to the very last record in the recordset same.
rsCustomer.EOF ' This method returns TRUE/FALSE to indicate if the record pointer is currently located at the end of the available
records.
rsCustomer.BOF ' [same for the start of the recordset] Note: If both EOF and BOF are TRUE then the recordset is empty.
rsCustomer.AddNew ' Creates a new blank record for you to place values in.
rsCustomer.Update ' Saves changes to a record back to the recordset, must be called after any modification and after using the
AddNew function.
rsCustomer.Delete ' Deletes the current record causes an error if there isn't a current record.
rsCustomer.RecordCount ' Property returning the number of records in the recordset. [Note: To ensure that the correct value is returned,
you should call the .MoveLast method first, otherwise this property may just return -1.]
rsCustomer.Close ' Closes the recordset
******************************************************************************************************
Recordset Open Options
******************************************************************************************************
rsCustomer.Open SQL, dbMain, adOpenStatic, adLockReadOnly
(1) SQL = Appropriate SQL statement (as shown below)
(2) dbMain = The Connection object that represents the database to be used, or a connection string, which would cause a new connection to
be created just for this recordset.
(3) adOpenStatic = Specifies which type of recordset should be opened. The choices are:
adOpenDynamic (Dynamic indicates one which we can modify)
adOpenForwardOnly
adOpenKeyset
adOpenStatic (Static is for opening the data as read-only)
(4) adLockReadOnly = The parameter which controls how the database handles record locking for edits performed on this recordset. The
choices are:
adLockBatchOptimistic (Batch setting is for advanced situations)
adLockOptimistic (Optimistic locking means that the database only locks the record when you go to save changes to it the least
amount of locking.)
adLockPessimistic (Pessimistic locking causes the database to lock the record as soon as you start working with it, resulting in a
longer locking time but necessary unless you want to be locked out (by someone else) in the middle of an edit).
adLockReadOnly (ReadOnly specifies that no locking is required, as changes to records will not be allowed).
Note: Other options are also allowed but not often used.
******************************************************************************************************
Database Connection Example
******************************************************************************************************
Public Sub CompleteDatabaseExample()
Dim dbMain as New ADODB.Connection ' Declaring the Connection
Dim rsCustomer as New ADODB.Recordset ' Declaring the Recordset
Dim SQL as String ' Declaring a simple variable
dbMain.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ ' Connecting to the Database
"Persist Security Info=False;" & _
"Data Source=C:\WINDOWS\Desktop\training.mdb"
SQL = "SELECT * FROM Customer" ' Setting up our SQL Command statement
rsCustomer.Open SQL, dbMain, adOpenDynamic, adLockOptimistic ' Opening the Recordset (see Recordset Options)
Do While Not rsCustomer.EOF ' Loop until we reach the End-Of-File marker
MsgBox "The Customer's Name is: " & rsCustomer("Name")
MsgBox "The Customer's City is: " & rsCustomer("City")
rsCustomer("Country") = "United States"
rsCustomer("Name") = rsCustomer("Name") & " Jr."
rsCustomer.Update ' Updating the Records (see also Recordset (Working With))
rsCustomer.MoveNext ' Moving to the next record (necessary to reach the EOF)
Loop
rsCustomer.Close ' Closing the recordset
dbMain.Close ' Closing the database connection
End Sub
******************************************************************************************************
Declaring a Recordset Object
******************************************************************************************************
Dim rsCustomer as New ADODB.Recordset
******************************************************************************************************
Closing a Database Connection
******************************************************************************************************
Public Sub OpenDatabaseConnection()
Dim dbMain as New ADODB.Connection
dbMain.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & "Persist Security Info=False;" & _
"Data Source=C:\WINDOWS\Desktop\training.mdb"
...
dbMain.Close
End Sub
Note (1): Using the Close method of the Connection object doesn't require any instruction; it takes no parameters and is called in th esame
manner as any other method.
Note (2): This method should always be called when you are done with your database connection; as it frees up system resources.
******************************************************************************************************
Opening a Database Connection
******************************************************************************************************
Public Sub OpenDatabaseConnection()
Dim dbMain as New ADODB.Connection
dbMain.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & "Persist Security Info=False;" & _
"Data Source=C:\WINDOWS\Desktop\training.mdb"
End Sub
Note (1): The string following the Open method above is known as the Connection String and can be created (and tested), if ADO is
installed on your machine, by going to the desktop and creating a new Microsoft Data Link object. Once the data link has been created it can
be opened as a text file and cut & pasted into your program.
******************************************************************************************************
Declaring a Database Connection Object
******************************************************************************************************
Dim dbMain As New ADODB.Connection
Note (1): Before we can declare any variable as ADO (ActiveX Data Objects the latest and greatest data access layer from Microsoft.
Which also supports accessing non-traditional data sources) objects, we need to add a reference to ADO to our project. Go to TOOLS |
REFERENCES and select the Microsoft ActiveX Data Objects 2.x library item.
Note (2): In our database-related projects (from Word) we will always start by creating an instance of a Connection object and opening a
connection to our database. When declaring your Connection variable, you need to use the New keyword, to specify that a new instance of
this object type should be created.
Note (3): This object supports two methods that are of primary interest: Open and Close, which link the object to a specific database and
remove that link, respectively.
******************************************************************************************************
SQL Query (Basic Syntax)
******************************************************************************************************
SELECT <Columns> FROM <Tables> WHERE <Criteria>
Example: SELECT * FROM Customer WHERE (City = "Los Angeles") AND (State = "CA")
Note (1): Columns are specified as a list of field names, separated by commas, like this: Name, Address, City. Field names that consist of
more than one word have to be surrounded by brackets [Street Address] in Access. Can also use an asterisk to specify all possible fields.
Note (2):The set of records from our database which matched the above criteria is represented in our code as a recordset, which is a special
type of database object.
******************************************************************************************************
SQL Query (Joining several tables on common field)
******************************************************************************************************
SELECT Customer.Name, Customer.City, Invoice.ID, Invoice.Date, Invoice.Notes FROM Customer, Invoice WHERE Customer.ID =
Invoice.[Customer] AND Customer.City = "Los Angeles"
Note (1): The query shown above joins the Customer and Invoice tables on their common fields (ID in the Customer Table and Customer in
the Invoice Table), which is accomplished through the use of an appropriate WHERE clause in the SQL statement.
Note (2): In your SQL statements, you can specify the table name in front of a field name to prevent any confusion. This is required if a
field by the same name exists in more than one of the tables involved in the query.
******************************************************************************************************