Free Web Hosting Provider - Web Hosting - E-commerce - High Speed Internet - Free Web Page
Search the Web

How-To-Tips

Access 2000


Categories

How to Add New Record to a Combo Box with Double-Click How to Animate the Office Assistant
How to Base Subforms on SQL Pass-Through Queries How to Bring a Subtotal from a Subform to a Main Form
How to Change the Order of Columns in a Chart How to Compare a Field to a Field in a Prior Record
How to Control How the User Closes a Form How to Control When Scroll Bars Are Displayed in a Subform
How to Create a "Please Wait" Message How to Create a Stopwatch Form
How to Create Do While and Do Until Loops in a Macro How to Create Running Totals in a Query
How to Delete Duplicate Records from a Table How to Determine If a Date Falls on a Weekend or Holiday
How to Display Line Numbers on Subform Records How to Display Only the Last Two Digits of Any Year
How to Edit Data in a Hyperlink Field in a Table How to Embed a Bitmap Object in a Report at Run Time
How to Filter a Report Using a Form's Filter How to FIND a Record Using ADO and Jet OLE DB Provider












Computer news    1A

How to Add New Record to a Combo Box with Double-Click

SUMMARY

This article describes how to set up a macro so that you can add new values to a combo box. The article uses the Orders form in the sample database Northwind.mdb as an example.

MORE INFORMATION

Follow these steps to modify the Orders form so that you can add new values to the Salesperson combo box:

CAUTION: Following the steps in this example will modify the sample database Northwind.mdb. You may want to back up the Northwind.mdb file and perform these steps on a copy of the database.

  1. Open the sample database Northwind.mdb.

  2. Create the following new macro, and save it as Macro1:

       Macro Name   Condition                   Action
       -----------------------------------------------------
       NewRecord                                OpenForm
       OnClose      [EmployeeID] Is Not Null    RunCommand
                    ...                         SelectObject
                    ...                         ReQuery
                    ...                         SetValue

       NewRecord Actions
       ---------------------------------------------------------
       OpenForm
          Form Name: Employees
          View: Form
          Data Mode: Add
          Window Mode: Normal

       OnClose Actions
       ----------------------------------------------
       RunCommand
          Command: SaveRecord
       SelectObject
          Object Type: Form
          Object Name: Orders
          In Database Window: No
       ReQuery
          ControlName: EmployeeId
       SetValue
          Item: [Forms]![Orders]![EmployeeID]
          Expression: [Forms]![Employees]![EmployeeID]
  3. Change the properties of the EmployeeID combo box on the Orders form as follows:

       OnDblClick: Macro1.NewRecord
       StatusBarText: Double-click to Add a New Employee
  4. Change the OnClose property of the Employees form as follows:

       On Close: Macro1.OnClose

To see how this works, open the Orders form in Form view, and then double-click the Salesperson combo box. Note that the Employees form opens. After you add a new record, close the Employees form. The new employee's name appears on the Orders form.


Computer news    2A

How to Animate the Office Assistant

SUMMARY

At times, you may want to animate the movements of the Office Assistant in response to actions performed in your application. For example, you may want to have the Assistant appear when you open a particular form. Or you may want the Assistant to react when a certain event is triggered. This article shows you how to do so.

MORE INFORMATION

The following example creates three event procedures that control the behavior of the Clippit Assistant. The first procedure selects Clippit and makes the Assistant visible when the Employees form is opened. The second procedure instructs Clippit to simulate listening to the computer when a field is updated. The third procedure closes the Assistant when the form is closed and resets some of the properties of the Assistant.

CAUTION: Following the steps in this example will modify the sample database Northwind.mdb. You may want to back up the Northwind.mdb file and perform these steps on a copy of the database.

NOTE: This example assumes you have the Clippit Assistant (Clippit.acs) installed on your computer. By default the Assistants are installed in the C:\Program Files\Microsoft Office\Office folder.

Starting the Assistant

  1. Open the sample database Northwind.mdb.

  2. Open the Employees form in Design view.

  3. Set the OnOpen property of the form to the following event procedure.

    NOTE: The following sample code requires that you have a reference to the Microsoft Office 9.0 Object Library in your database. To create the reference, open any module in Design view, click References on the Tools menu, and then click the Microsoft Office 9.0 Object Library.

    Private Sub Form_Open(Cancel As Integer)
       With Assistant
          .Filename = "Clippit.acs"   ' Returns or sets the name of the
                                      ' active Office Assistant.
          .Visible = True
          .Animation = msoAnimationGreeting   ' Simulates greeting user.
          .Sounds = True
          .SearchWhenProgramming = True
          .FeatureTips = True
       End With
    End Sub
  4. On the File menu, click "Close and Return to Microsoft Access."

Changing the Movement of the Assistant

  1. Set the AfterUpdate property of the FirstName text box to the following event procedure:

    Private Sub FirstName_AfterUpdate()
       With Assistant
          .Animation = msoAnimationListensToComputer  ' Animates
                                                      ' Assistant.
       End With
    End Sub
  2. On the File menu, click "Close and Return to Microsoft Access."

Closing the Assistant When the Form Closes

  1. Set the OnClose property of the form to the following event procedure:

    Private Sub Form_Close()
       If Assistant.Visible = True Then
          With Assistant
             .AssistWithHelp = False
             .SearchWhenProgramming = False
             .GuessHelp = False
             .FeatureTips = False
             .Visible = False
          End With
       End If
    End Sub
  2. On the File menu, click "Close and Return to Microsoft Access."

  3. Save the form, and then open it in Form view. Note that the Clippit Assistant is displayed.

  4. Type a new name in the First Name field and press ENTER. Note that the Clippit Assistant responds with "listening" animation.

  5. Close the form. Note that the Clippit Assistant closes.

REFERENCES

For more information about using the Office Assistant, click Microsoft Access Help on the Help menu, type Assistant in the Office Assistant or the Answer Wizard, and then click Search to view the topics returned.

To see a list of file names that correspond to the different Office Assistants, from the Visual Basic Editor, click Microsoft Visual Basic on the Help menu, type "Filename property" in the Office Assistant or the Answer Wizard, and then click Search to view the topic.


Top    3A

How to Base Subforms on SQL Pass-Through Queries

SUMMARY

This article shows you how to use an SQL pass-through query for a form's record source. It assumes that you know how to build and use SQL pass-through queries.

You should keep the following considerations in mind when you use SQL pass-through queries for record sources of forms:

MORE INFORMATION

SQL Pass-Through Queries Are Read-Only

Forms based on SQL pass-through queries are read-only because SQL pass- through queries are read-only. The recordset returned by an SQL pass- through query is a snapshot, or read-only recordset. This behavior is by design. In order for the form to be updateable, base your form on a linked table with a unique index.

The Query Builder Does Not Save the Connect String

The Query Builder of the RecordSource property displays a window that looks similar to the Design window of a query. You use this window to build the SQL string or query for the RecordSource property. The Query Builder will set the RecordSource property to an SQL string if the SQL string is not saved as a query. If you save the string as a query, the name of the query will be used as the RecordSource property.

When you are using an SQL pass-through query created by using the Query Builder, the ODBC connect string defined in that query will not be returned as part of the RecordSource property SQL string. This can produce the following error message:

Couldn't find input table or query '[Table from ODBC Server]'

Without the ODBC connect string, the form will look for a local table, instead of a table on the server. If you save the SQL string as a query, the RecordSource property will contain the name of the query instead of the SQL string, and the form will be able to retrieve the remote data correctly.

SQL Pass-Through Queries cannot use LinkChildFields/LinkMasterFields

The best way to use server-based data in a subform is to link the remote table and then base the subform on the linked table.

If you base a subform directly on an SQL pass-through query, you may receive the following error message when you open the form:

You can't use a pass-through query or a non-fixed column crosstab query as a record source for a subform or subreport.


This error occurs if you have LinkMasterFields and LinkChildFields defined for the subform or subreport.

REFERENCES

For more information about SQL pass-through queries, click Microsoft Access Help on the Help menu, type "pass-through queries" in the Office Assistant or the Answer Wizard, and then click Search to view the topic.


Top    4A

How to Bring a Subtotal from a Subform to a Main Form

SUMMARY

This article shows you how to reference a subtotal control on a subform from a main form.

MORE INFORMATION

If you try to sum a subform field by using a calculated control on a main form, you may receive an error message in the main form control. For example, the following expression in a main form control generates a "#Name?" error message:


   =Sum([MySubForm].Form![ExtendedPrice]) 

To avoid an error, you can sum the subform field by using a calculated control in the subform's form footer. You can then reference the calculated control from the main form to display the summed value.

There's an example of this method in the Orders form of the Northwind sample database. First, a calculated control in the footer of the Orders Subform sums the subform's Extended Price field to create a subtotal. It uses the following syntax:


   Text Box Control
   ----------------
   Name: OrderSubtotal
   ControlSource: =Sum([ExtendedPrice]) 

Because the subform's DefaultView property is set to Datasheet, you do not see the calculated control in the subform's form footer when you open the Orders form in Form view. However, a text box control on the main Orders form refers to the subform's calculated control and gets its value to display. The main form control is called Subtotal and references the subform's calculated control. It uses the following syntax:


   Text Box Control
   ----------------
   Name: Subtotal
   ControlSource: =[Orders Subform].[Form]![OrderSubtotal] 

This reference allows the main form to display a subtotal of a subform control while the actual totaling of subform values is performed by using a calculated control in the subform's form footer.

REFERENCES

For more information about referencing subform controls, click Microsoft Access Help on the Help menu, type "calculating a total in a subform" in the Office Assistant or the Answer Wizard, and then click Search to view the topic.


Top    5A

How to Change the Order of Columns in a Chart

SUMMARY

By default, a chart sorts the X-axis fields in alphabetical or numeric order. This article describes two methods that you can use to sort the X-axis fields in a different order.

MORE INFORMATION

There are two methods you can use to change the ordering of fields in a chart. The first way is to add an ORDER BY clause to the SQL statement in the chart's RowSource property. The second way is to create a query that orders the fields the way that you want them, and then to use the query for the chart's RowSource property.

CAUTION: Following the steps in this example will modify the sample database Northwind.mdb. You may want to back up the Northwind.mdb file and perform these steps on a copy of the database.

How to Create a Sample Chart

To create a chart, follow these steps:

  1. Open the sample database Northwind.mdb.

  2. Create a new, blank form not based on any table or query.

  3. On the Insert menu, click Chart, and then click in the detail section of the form where you want the chart to appear.

  4. In the Chart Wizard dialog box, select the Sales By Category query as the data source for the chart, and then click Next.

  5. Add the CategoryName and ProductSales fields to the Fields For Chart box, and then click Finish.

  6. View the form in Form view. Note that the CategoryName records are listed in alphabetical order.

How to Change the Chart's Sorting Order

Method 1

The following example demonstrates how to add an ORDER BY clause to the SQL statement in a chart's RowSource property:

  1. Open the form that you created in the section "How to Create a Sample Chart" in Design view.

  2. Select the chart.

  3. If the property sheet is not displayed, on the View menu, click Properties.

  4. Select the RowSource property of the chart, and then press SHIFT+F2 to zoom in on the window. Note that the RowSource property's SELECT statement reads as follows:

    SELECT [CategoryName],Sum([ProductSales]) AS [SumOfProductSales] FROM [Sales by Category] GROUP BY [CategoryName];

  5. Type Order By SUM([ProductSales]) desc before the semicolon at the end of the SQL statement so that the SQL statement reads as follows:

    SELECT [CategoryName],Sum([ProductSales]) AS SumOfProductSales] FROM [Sales by Category] GROUP BY [CategoryName] Order By SUM([ProductSales]) desc;

  6. Click OK.

  7. View the form in Form view. Note that the CategoryName records are now listed in descending order of sales.

Method 2

The following example describes how to create and use a query for the chart's RowSource property:

  1. Re-create the form with a chart that you created in the section "How to Create a Sample Chart."

  2. Select the chart.

  3. If the property sheet is not displayed, on the View menu, click Properties.

  4. Using the right mouse button, click the RowSource property, and then click Build.

  5. In the SQL Statement: Query Builder window, set the sort order for the ProductSales field to Descending.

  6. Close the SQL Statement: Query Builder window and save the changes.

  7. View the form in Form view. Note that the CategoryName records are listed in descending order of sales.

REFERENCES

For more information about ordering fields, click Microsoft Access Help on the Help menu, type "ORDER BY clause" in the Office Assistant or the Answer Wizard, and then click Search to view the topic.


Top    6A

How to Compare a Field to a Field in a Prior Record

SUMMARY

This article shows you how to use a subquery to compare the values in a record with the values in another record. In order to use the method described in this article, the table that you are using must have one or more fields that can be compared by using the Greater Than (>) or Less Than (<) operator.

MORE INFORMATION

The following example demonstrates how to calculate miles per gallon by subtracting a recorded mileage from the current mileage, and then dividing by the number of gallons of gasoline recorded in the current record. The example is divided into two sections: one for an Access database, and the other for an Access project.

In a Microsoft Access database (MDB)

  1. Create the following new table, and then save it as MileageRecord. Do not create a primary key for the table:

       Table: MileageRecord
       --------------------
       Field Name: Date
        Data Type: Date/Time
       Field Name: Mileage
        Data Type: Number
       Field Size: Single
       Field Name: Gallons
        Date Type: Number
        Field Size: Double
  2. View the table in Datasheet view, and enter the following records in the table:

       Date        Mileage   Gallons
       -----------------------------
       7/08/1999   12340     14.8
       7/13/1999   12700     12.6
       7/18/1999   13090     13.7
       7/25/1999   13425     11.9
  3. Create a new, blank query based on the MileageRecord table. Add the Date and Mileage fields to the query grid.

  4. Click the Properties button on the toolbar to view the property sheet, and then select the title bar of the MileageRecord table. Set the Alias property of the table to Mile1.

  5. Enter the following expression in the third column in the query grid.

    NOTE: In the following sample expression, an underscore (_) at the end of a line is used as a line-continuation character. Remove the underscore from the end of the line when re-creating this expression.
    
       PrevMileage: (Select Max(Mileage) from MileageRecord _
       Where Mileage < Mile1.[Mileage]) 

    This expression is a subquery that finds the highest mileage in the MileageRecord table that is less than the mileage of the current record.

  6. Enter the following expression in the fourth column in the query grid:
    
       Elapsed: [Mileage] - [PrevMileage] 

    This field calculates the difference between the current and previous mileage entries.

  7. Enter the following expression in the fifth column in the query grid:
    
       MPG: ([Mileage] - [PrevMileage]) / Gallons 

    This field calculates the miles per gallon.

  8. Run the query.

In a Microsoft Access project (ADP)

  1. Create the following new table, and then save it as MileageRecord:

       Table: MileageRecord
       --------------------
       Column Name: ID
        Datatype: uniqueidentifier
        Allow Nulls: no
        Default Value: newid()
       Column Name: Date
        Datatype: datetime
       Column Name: Mileage
        Datatype: decimal
        Length: 9
        Precision: 18
        Scale: 2
       Column Name: Gallons
        Datatype: decimal
        Length: 9
        Precision: 18
        Scale: 2
  2. View the table in Datasheet view, and enter the following records in the table:

       Date        Mileage   Gallons
       -----------------------------
       7/08/1999   12340     14.8
       7/13/1999   12700     12.6
       7/18/1999   13090     13.7
       7/25/1999   13425     11.9
  3. Create the following stored procedure:

    CREATE PROCEDURE "Calculate_Mileage_Proc"
    AS
    SELECT
      MileageRecord.Date,
      MileageRecord.Mileage,
      (SELECT MAX(mileage)
        FROM mileagerecord
        WHERE mileagerecord.mileage < mileagerecord1.mileage)
        AS PrevMileage,
      MileageRecord.Mileage - (SELECT MAX(mileage)
        FROM mileagerecord
        WHERE mileagerecord.mileage < mileagerecord1.mileage)
        AS Elapsed,
      (MileageRecord.Mileage - (SELECT MAX(mileage)
        FROM mileagerecord
        WHERE mileagerecord.mileage < mileagerecord1.mileage))
        / MileageRecord.Gallons
        AS MPG

    FROM MileageRecord

    INNER JOIN
     MileageRecord MileageRecord1 ON
     MileageRecord.id = MileageRecord1.id
  4. Save and run the stored procedure.

Results

Note that you receive the following results from the query or the stored procedure:


   Date      Mileage   PrevMileage   Elapsed   MPG
   ------------------------------------------------------------
   7/08/99   12340
   7/13/99   12700     12340         360       28.5714285714286
   7/18/99   13090     12700         390       28.4671532846715
   7/25/99   13425     13090         335       28.1512605042017 

REFERENCES

For more information about subqueries, click Microsoft Access Help on the Help menu, type "SQL subqueries" in the Office Assistant or the Answer Wizard, and then click Search to view the topic.


Top    7A

How to Control How the User Closes a Form

SUMMARY

A Microsoft Access form has a CloseButton property, which you can use to prevent a user from closing the form with either the Close Button icon or by clicking Close on the File menu. However, the user can still close the form by pressing ALT+F4. This article shows you how to prevent the user from closing a form by pressing ALT+F4.

CAUTION: Following the steps in this example will modify the sample database Northwind.mdb. You may want to back up the Northwind.mdb file and perform these steps on a copy of the database.

This example prevents the user from using ALT+F4 to close a form:

  1. Open the sample Microsoft Access database file Northwind.mdb or the sample Microsoft Access Project file NorthwindCS.adp.

  2. Open the Customers form in Design view.

  3. Change the following property:

       Form: Customers
       -------------------------
       CloseButton: No
  4. On the View menu, click Code.

  5. Type the following lines in the Declarations section:


    Option Explicit
    Public blnClose As Boolean
  6. Add the following line of code to the Load event of the form:


    blnClose = False
  7. Add the following control to the form:

       Command Button
       -------------------
       Name: cmdCloseForm
       Caption: &Close
  8. Add the following line of code to the Click event of the command button, cmdCloseForm:


    blnClose = True
    DoCmd.Close acForm, "Customers", acSaveNo
  9. Add the following code to the UnLoad event of the form:


       Dim strMessage As String
       Dim intStyle As Integer
       Dim strTitle As String

       strMessage = "You are attempting to close this form incorrectly." & _
          vbCrLf & "Please try again using the designated Close Button"
       intStyle = vbOKOnly + vbCritical
       strTitle = "Closing Customers?"

       If blnClose = False Then
          MsgBox prompt:=strMessage, buttons:=intStyle, Title:=strTitle
          Cancel = True
       End If
     
  10. Open the Customers form in Form view.

    Note that the Close Button icon button remains visible but appears dimmed (grayed). Clicking Close on the File menu causes the custom message to be displayed. This message is also displayed if the user presses ALT+F4.

REFERENCES

For more information about events, in the Visual Basic Editor, click Microsoft Visual Basic Help on the Help menu, type "events and event properties Reference" in the Office Assistant or the Answer Wizard, and then click Search to view the topic.


Top    8A

How to Control When Scroll Bars Are Displayed in a Subform

SUMMARY

Moderate: Requires basic macro, coding, and interoperability skills.

You may want to display scroll bars in a subform only as needed. The following function turns the scroll bars on or off according to a preset number. The scroll bars do not appear unless the number of records in the subform is greater than the preset number.

MORE INFORMATION

The following example demonstrates how to use an event procedure in the OnCurrent property of the subform to display or hide the scroll bars:

  1. Start Microsoft Access and open the sample database Northwind.mdb.

  2. Open the Quarterly Orders Subform form in Design view.

  3. Set the OnCurrent property of the subform to the following event procedure:


    Private Sub Form_Current()

       ' If the number of records in the subform
       ' is greater than 4, display the
       ' horizontal and vertical scrollbars.
       If Me.RecordsetClone.RecordCount > 4 Then
          Me.ScrollBars = 3
       Else
          Me.ScrollBars = 0
       End If

    End Sub
     
  4. Close the Quarterly Order Subform form and save the changes.

  5. Open the Quarterly Orders form and note that the subform is designed to display four records at a time.

  6. Use the record selectors to scroll through the records on the main form, and note that the scrollbars appear only when needed to view additional records on the subform.

REFERENCES

For more information about the ScrollBars property, click Microsoft Access Help on the Help menu, type "ScrollBars property" in the Office Assistant or the Answer Wizard, and then click Search to view the topic.


Top    9A

How to Create a "Please Wait" Message

SUMMARY

Sometimes you may want to display a status message to inform users that they must wait for an action to be completed. For example, you may want to display the text "Please Wait" while Microsoft Access is initializing a database, running a long query, and so on. This article uses the sample database Northwind.mdb to show you how to create a "Please Wait" message.

MORE INFORMATION

To display a status message in Microsoft Access, do the following:

  1. Create the following form not based on any table or query:
    
       Form: PleaseWait
       ---------------------
       Caption: TestForm
       ScrollBars: Neither
       Popup: Yes
       Modal: Yes
       RecordSelectors: No
       NavigationButtons: No
    
       Label
       --------------------
       Caption: Please Wait
       Font Size: 18 

    The label caption is the message you want to display.

  2. Create the following macro named Test1:
    
       Macro Name             Action
       -----------------------------
       Test1                  OpenForm
                              RepaintObject
                              OpenQuery
                              Close
    
       Test1 Actions
       -----------------------------
       OpenForm
       Form Name: PLEASEWAIT
       View: Form
       Data Mode: Read Only
       Window Mode: Normal
    
       RepaintObject
       Object Type: Form
       Object Name: PLEASEWAIT
    
       OpenQuery
       Query Name: Order Details Extended
       View: Datasheet
    
       Close
       Object Type: Form
       Object Name: PLEASEWAIT
       Save: No 

    NOTE: The above argument for OpenQuery is just an example of what you may want to run; this can be anything. The main macro actions in Test1 are OpenForm, RepaintObject, and Close.

  3. Run the macro. Note that the PleaseWait form opens. As soon as the query completes processing, the form disappears and the query results appear.

Top    10A

How to Create a Stopwatch Form

The following example demonstrates how to create and use a form to track elapsed time:

  1. Open any database.

  2. Create a blank form not based on any table or query and set the following properties for the form:

       ScrollBars: Neither
       RecordSelectors: No
       NavigationButtons: No
       OnTimer: [Event Procedure]
       TimerInterval: 0
  3. Add a text box to the form and set the following properties for the text box:

       Name: ElapsedTime
       DefaultValue: "00:00:00:00"
       Enabled: No
       Locked: Yes
  4. Add a command button to the form and set the following properties for the command button:

       Name: btnStartStop
       Caption: Start
       OnClick: [Event Procedure]
  5. Add a second command button to the form and set the following properties for the second command button:

       Name: btnReset
       Caption: Reset
       OnClick: [Event Procedure]
  6. Click Code on the View menu to open the editor. Type the following lines in the Declarations section:

    Option Explicit
    Dim TotalElapsedMilliSec As Long
    Dim StartTickCount As Long
    Private Declare Function GetTickCount Lib "kernel32" () As Long
  7. Set the OnTimer property of the form to the following event procedure:


    Private Sub Form_Timer ()

       Dim Hours As String
       Dim Minutes As String
       Dim Seconds As String
       Dim MilliSec As String
       Dim Msg As String
       Dim ElapsedMilliSec As Long

       ElapsedMilliSec = (GetTickCount() - StartTickCount) + _
          TotalElapsedMilliSec

       Hours = Format((ElapsedMilliSec \ 3600000), "00")
       Minutes = Format((ElapsedMilliSec \ 60000) Mod 60, "00")
       Seconds = Format((ElapsedMilliSec \ 1000) Mod 60, "00")
       MilliSec = Format((ElapsedMilliSec Mod 1000) \ 10, "00")

       Me!ElapsedTime = Hours & ":" & Minutes & ":" & Seconds & ":" _
          & MilliSec

    End Sub
  8. Set the OnClick property of the btnStartStop command button to the following event procedure:

    Private Sub btnStartStop_Click()

       If Me.TimerInterval = 0 Then
          StartTickCount = GetTickCount()
          Me.TimerInterval = 15
          Me!btnStartStop.Caption = "Stop"
          Me!btnReset.Enabled = False
       Else
          TotalElapsedMilliSec = TotalElapsedMilliSec + _
             (GetTickCount() - StartTickCount)
          Me.TimerInterval = 0
          Me!btnStartStop.Caption = "Start"
          Me!btnReset.Enabled = True
       End If

    End Sub
     
  9. Set the OnClick property of the btnReset command button to the following event procedure:

    Private Sub btnReset_Click()
       TotalElapsedMilliSec = 0
       Me!ElapsedTime = "00:00:00:00"
    End Sub
  10. Open the form in Form view to test the stop watch.

Top   11A

How to Create Do While and Do Until Loops in a Macro

SUMMARY

To perform a Do While or Do Until loop in a Microsoft Access macro, you need to use a combination of correct macro structure and the RunMacro action with appropriate information supplied in the Repeat Expression parameter. These requirements are described in more detail later in this article.


MORE INFORMATION

There are several types of Do loops. Each type handles the looping procedure and conditions differently. The different types of Do loops are as follows:

  1. Do While <condition>... Loop

    This loop will execute while the condition is true. If the loop is encountered and the condition is already false, the loop will not be performed.

  2. Do Until <condition>... Loop

    This loop will execute until the condition is true. If the loop is encountered and the condition is already true, the loop will not be performed.

  3. Do... Loop While <condition>

    This loop will execute the first time unconditionally, and then loop while the condition is true. If the loop is encountered and the condition is already false, the loop will be performed once.

  4. Do... Loop Until <condition>

    This loop will execute the first time unconditionally, and then loop until the condition is true. If the loop is encountered and the condition is already true, the loop will be performed once.

To perform a Do While or Do Until loop in a macro, use a macro similar to the following examples. To create the following examples, open a new macro and click Macro Names on the View menu. Add the following macro names and actions and save this macro group as Do_Loops.

Do While <Condition>... Loop and Do Until <Condition>... Loop


   Macro Name       Action
   -------------------------
   Do_Loop1         RunMacro
   Loop1            MsgBox

   Do_Loop1 Actions
   --------------------------------------
   RunMacro
      Macro Name: Do_Loops.Loop1
      Repeat Expression: <your_condition>

   Loop1 Actions
   -------------------
   MsgBox
      Message: ="Loop" 

In this example, the Do_Loop1 macro calls the Loop1 macro while the Repeat Expression parameter of the RunMacro action is true.

Do... Loop While <Condition> and Do... Loop Until <Condition>


   Macro Name       Action
   -------------------------
   Do_Loop1         RunMacro
                    RunMacro
   Loop1            MsgBox

   Do_Loop1 Actions
   --------------------------------------
   RunMacro
      Macro Name: Do_Loops.Loop1
   RunMacro
      Macro Name: Do_Loops.Loop1
      Repeat Expression: <your_condition>

   Loop1 Actions
   -------------------
   MsgBox
      Message: ="Loop"
 

In this example, the Do_Loop1 macro calls the Loop1 macro once unconditionally, and then continues to call the Loop1 macro while the Repeat Expression parameter of the RunMacro action is True.

Conditions

The condition used in the loop, which is supplied in the Repeat Expression parameter of the RunMacro action, can be based on a value in a field on a form, a property of a control on a form, or the value returned from a Visual Basic function. If the condition is based on a field in a form or a property of a control on a form, it will have syntax similar to:

Forms![CounterForm]![Counter]<=10

-or-

Forms![EntryForm]![InvoiceNo].Visible=True

If the condition is based on the value returned from a Visual Basic function, it will have syntax similar to:


Time()>=TimeEntry() 

Do While Loops vs. Do Until Loops

Whether a loop is a Do While loop or a Do Until loop depends on the condition. The RunMacro action runs the macro until the condition in the Repeat Expression parameter is false. This behavior is exactly what is needed for a Do While loop. It is, however, the opposite of what is needed for a Do Until loop. Therefore, to make a condition for a Do Until loop work correctly, precede the condition in the RunMacro action with the NOT operator.


Top    12A

How to Create Running Totals in a Query

SUMMARY

This article demonstrates two methods that you can use to create a running totals query. A running totals query is a query in which the total for each record is a summation of that record and any previous records. This type of query is useful for displaying cumulative totals over a group of records (or over a period of time) in a graph or report.

MORE INFORMATION

Method 1

The first method uses a DSum() function and criteria in a query to create a running sum over time. The DSum() function sums the current record and any previous records. When the query moves to the next record, the DSum() function runs again and updates the cumulative total.

The following sample query uses the Orders table from the sample database Northwind.mdb to create a running sum of the freight costs for each month in 1997. The sample data is limited to one year for performance reasons. Because the DSum() function runs once for every record in the query, it may take several seconds (depending on the speed of your computer) for the query to finish processing. To create and run this query, follow these steps:

  1. Open the sample database Northwind.mdb.

  2. Create a new select query and add the Orders table.

  3. On the View menu, click Totals.

  4. In the first column of the query design grid, type the following expression in the Field box, and make the following selections for the Total, Sort, and Show boxes:
    
       Field: AYear: DatePart("yyyy",[OrderDate])
       Total: Group By
       Sort: Ascending
       Show: Yes 

    The expression in the Field box displays and sorts the year portion of the OrderDate field.

  5. In the second column of the query design grid, type the following expression in the Field box, and make the following selections for the Total, Sort, and Show boxes:
    
       Field: AMonth: DatePart("m",[OrderDate])
       Total: Group By
       Sort: Ascending
       Show: Yes 

    The expression in the Field box sorts and displays the month portion of the Order Date field as an integer value from 1 to 12.

  6. In the third column of the query design grid, type the following expression in the Field box, and make the following selections for the Total and Show boxes.

    NOTE: In the following example, an underscore (_) at the end of a line is used as a line-continuation character. Remove the underscore from the end of the line when re-creating this example.
    
       Field: RunTot: DSum("Freight","Orders","DatePart('m', _
              [OrderDate])<=" & [AMonth] & " And  DatePart('yyyy', _
              [OrderDate])<=" & [AYear] & "")
       Total: Expression
       Show: Yes 

    The expression in the Field box uses the DSum() function to sum the Freight field when the values in both the AMonth and the AYear fields are less than or equal to the current record that the query is processing.

  7. In the fourth column of the query design grid, type the following expression in the Field box, and make the following selections for the Total, Sort, and Show boxes:
    
       Field: FDate: Format([OrderDate],"mmm")
       Total: Group By
       Sort: Ascending
       Show: Yes 

    The expression in the Field box displays each month in a textual format, such a Jan, Feb, Mar, and so on.

  8. In the fifth column of the query design grid, type the following expression in the Field box, and make the following selections for the Total, Criteria, and Show boxes:
    
       Field: DatePart("yyyy",[OrderDate])
       Total: Where
       Criteria: 1997
       Show: No 

    The expression in the Field box filters the query's recordset to include data from 1997 only.

  9. Run the query.

    Note that the RunTot field displays the following records with a running sum:
    
       AYear    AMonth     RunTot       FDate
       --------------------------------------
       1997     1          2238.98      Jan
       1997     2          3840.43      Feb
       1997     3          5729.24      Mar
       1997     4          8668.34      Apr
       1997     5          12129.74     May
       1997     6          13982.39     Jun
       1997     7          17729.29     Jul
       1997     8          22204.73     Aug
       1997     9          26565.26     Sep
       1997     10         32031.38     Oct
       1997     11         36192.09     Nov
       1997     12         42748.64     Dec 

Method 2

The second method uses a totals query with a DSum() function to create a running total over a group.

The following sample query uses the Orders table to sum freight costs per employee as well as to calculate a running sum of the freight. To create and run the query, follow these steps:

  1. Open the sample database Northwind.mdb.

  2. Create a new select query and add the Orders table.

  3. On the View menu, click Totals.

  4. In the first column of the query design grid, add the following field to the Field box, and make the following selections for the Total and Show boxes:
    
       Field: EmpAlias: EmployeeID
       Total: Group By
       Show: Yes 

    This field groups data by EmployeeID.

  5. In the second column of the query design grid, add the following field to the Field box, and make the following selections for the Total and Show boxes:
    
       Field: Freight
       Total: Sum
       Show: Yes 

    This field sums the freight data.

  6. In the third column of the query design grid, type the following expression in the Field box, and make the following selections for the Total and Show boxes.

    NOTE: In the following example, an underscore (_) at the end of a line is used as a line-continuation character. Remove the underscore from the end of the line when re-creating this example.
    
       Field: RunTot: Format(DSum("Freight","Orders","[EmployeeID]<=" _
              & [EmpAlias] & ""),"$0,000.00")
       Total: Expression
       Show: Yes 

    The expression in the Field box uses a DSum() function to sum the Freight field when the EmployeeID is less than or equal to the current EmpAlias, and then formats the field in dollars.

  7. Run the query.

    Note that the RunTot field displays the following records with a running sum:
    
       Employee              SumOfFreight     RunTot
       -------------------------------------------------
       Davolio, Nancy        $8,836.64        $8,836.64
       Fuller, Andrew        $8,696.41        $17,533.05
       Leverling,Janet       $10,884.74       $28,417.79
       Peacock, Margaret     $11,346.14       $39,763.93
       Buchanan, Steven      $3,918.71        $43,682.64
       Suyama, Michael       $3,780.47        $47,463.11
       King, Robert          $6,665.44        $54,128.55
       Callahan, Laura       $7,487.88        $61,616.43
       Dodsworth, Anne       $3,326.26        $64,942.69 

REFERENCES

For more information about totals queries, click Microsoft Access Help on the Help menu, type perform calculations in a query in the Office Assistant or the Answer Wizard, and then click Search to view the topics returned.


Top    13A

How to Delete Duplicate Records from a Table

SUMMARY

This article describes how you can remove duplicate records from a table by using primary keys. By using this method, you can check for duplicate values in up to 10 fields in the table.

MORE INFORMATION

To remove duplicate records from a table, follow these steps:

  1. Make a copy of the structure of the table from which you want to remove the duplicate records.

    To copy a table:

    1. Select the table in the Database window

    2. On the Edit menu, click Copy.

    3. On the Edit menu, click Paste.

    4. Enter a name for the new table.

    5. Select Structure Only

    6. Click OK.

  2. Open the new table in Design view.

  3. Select the field(s) that contain the duplicate values.

  4. To make your selection the primary key for the table, click the Primary Key button on the toolbar.

  5. Save and close the table.

  6. Create an append query based on the original table containing duplicates.

  7. In the query Design View, on the Query menu, click Append Query.

  8. In the Append dialog box, click the name of the new table from the Table Name list, and then click OK.

  9. Include all the fields from the original table by dragging the asterick (*) to the query design grid.

  10. On the Query menu, click Run.

  11. Click Yes in the dialog box advising you that you are about to append records.

  12. Because the Primary Key field(s) in the new table will not accept duplicate values, the following error message will be displayed:

    Microsoft Access can't append all the records in the append query.

    Microsoft Access set 0 field(s) to Null due to a type conversion failure, and it didn't add <number> record(s) to the table due to key violations, 0 record(s) due to lock violations, and 0 record(s) due to validation rule violations.
    Do you want to run the action query anyway?
    To ignore the error(s) and run the query, click Yes. For an explanation of the causes of the violations, click Help.
  13. Click Yes.

  14. View the contents of the new table. When you're sure the new table has the correct unique records, you can delete the original table, and then rename the new table using the name of the original table.

REFERENCES

For more information about deleting duplicate records, click Microsoft Access Help on the Help menu, type "Automatically delete duplicate records from a table." in the Office Assistant or the Answer Wizard, and then click Search to view the topic.


Top    14A

How to Determine If a Date Falls on a Weekend or Holiday

SUMMARY

This article shows you how to create a Visual Basic for Applications function to determine if a date falls on a weekend or holiday. This example is useful for setting due dates in applications that have billing or invoicing features.

MORE INFORMATION

The following example uses the WeekDay() function to determine if a specific date falls on a Saturday or Sunday. Then, it uses a DLookup() function to determine if it falls on a date stored in a user-created Holidays table.

Creating a Holidays Table

The following example requires a table with a particular structure for storing Holiday dates. To create the table and sample records, follow these steps:

  1. Create a new table in Design view and add the following fields:


       Table: Holidays
       -----------------------
       Field Name: Description
         Data Type: Text
       Field Name: HoliDate
         Date Type: Date/Time
  2. Save the table as Holidays and switch the table to Datasheet view. Add the following records:


       Description                         HoliDate
       --------------------------------------------
       New Year's Day                      1/1/2000
       Martin Luther King, Jr. Day (USA)   1/15/2000
       Memorial Day (observed-USA)         5/29/2000
       Labor Day (USA)                     9/4/2000
  3. Close and save the Holidays table.

Creating the Custom Function

To create a function that determines if a date falls on a weekend or holiday, follow these steps:

  1. Create a new module in Design view.

  2. Add the following function:

    Function OfficeClosed(TheDate) As Integer
      
       OfficeClosed = False

       ' Test for Saturday or Sunday.
       If WeekDay(TheDate) = 1 Or WeekDay(TheDate) = 7 Then
           OfficeClosed = True
       ' Test for Holiday.
       ElseIf Not IsNull(DLookup("HoliDate", "Holidays", "[HoliDate]=#" _
         & TheDate & "#")) Then
           OfficeClosed = True
       End If

    End Function
  3. To test this function, type the following line into the Immediate window, and then press ENTER:

    ? OfficeClosed(#9/4/2000#)

    Note that this returns a True value (-1) because 9/4/2000 is listed in the Holidays table.

Usage Example

You can use the custom OfficeClosed() function to calculate due dates. For example, if your office or business is closed for a three-day weekend, you may want to extend your customers' grace period for their outstanding bills. Here's sample code for adding one more day to a grace period:


DueDate=OrderDate+30
Do While OfficeClosed(DueDate)
   DueDate=DateDue+1
Loop 

REFERENCES

For more information about the Weekday() function, in the Visual Basic Editor, click Microsoft Visual Basic Help on the Help menu, type weekday function in the Office Assistant or the Answer Wizard, and then click Search to view the topic.


Top   15A

How to Display Line Numbers on Subform Records

SUMMARY

This article shows you how to create and use a procedure to display the current line or row number in a subform.

MORE INFORMATION

The following examples demonstrate how to create and use the sample function, GetLineNumber().

NOTE: The sample code in this article uses Microsoft Data Access Objects. For this code to run properly, you need to reference the Microsoft DAO 3.6 Object Library.

How to Create the GetLineNumber() Function

  1. Open the sample database Northwind.mdb.

  2. Create a module and type the following line in the Declarations section:


    Option Explicit
  3. Type the following procedure:


    Function GetLineNumber (F As Form, KeyName As String, KeyValue)

       Dim RS As DAO.Recordset
       Dim CountLines

       On Error GoTo Err_GetLineNumber

       Set RS = F.RecordsetClone

       ' Find the current record.
       Select Case RS.Fields(KeyName).Type
          ' Find using numeric data type key value.
          Case dbInteger, dbLong, dbCurrency, dbSingle, dbDouble, dbByte
             RS.FindFirst "[" & KeyName & "] = " & KeyValue
             ' Find using date data type key value.
          Case dbDate
             RS.FindFirst "[" & KeyName & "] = #" & KeyValue & "#"
             ' Find using text data type key value.
          Case dbText
             RS.FindFirst "[" & KeyName & "] = '" & KeyValue & "'"
          Case Else
             MsgBox "ERROR: Invalid key field data type!"
             Exit Function
       End Select

       ' Loop backward, counting the lines.
       Do Until RS.BOF
          CountLines = CountLines + 1
          RS.MovePrevious
       Loop

    Bye_GetLineNumber:
       ' Return the result.
       GetLineNumber = CountLines

       Exit Function

    Err_GetLineNumber:
       CountLines = 0
       Resume Bye_GetLineNumber

    End Function

The GetLineNumber() function requires the following three parameters:

You could use the following sample expression as the ControlSource property setting of a text box on a subform, given that the subform's underlying table has a field called ID as its unique key field:


=GetLineNumber(Form,"ID",[ID]) 

How to Use the GetLineNumber() Function

CAUTION: Following the steps in this example will modify the sample database Northwind.mdb. You may want to back up the Northwind.mdb file and perform these steps on a copy of the database.

  1. Open the Order Details table in Design view, add the following field to the table, and then save the table:
    
       Field Name: ID
       Data Type:  AutoNumber 

    This field will serve as the required single unique field for the table.

  2. Open the Order Details Extended query in Design view, add the ID field from the Order Details table to the query grid, and then save the query.

  3. Open the Orders Subform form in Design view and add the following text box to the form:

       Name: LineNum
       ControlSource: =GetLineNumber([Form], "ID", [ID])
  4. On the View menu, click Tab Order. Drag the LineNum field from the bottom of the Custom Order list to the top, and then click OK.

  5. Save and close the Orders Subform.

  6. Open the Orders form in Form view and move to a record with multiple order line items. Note that the LineNum text box displays the record number for each product in the order.

Top    16A

How to Display Only the Last Two Digits of Any Year

SUMMARY

This article describes how to display only the last two digits of the year.

The expression

=Year(Now())

displays all four digits of the current year (for example, 1999).

In order to display only the last two digits of the year (for example, 99), use one of the following expressions:

=Format(Now(),"yy")

-or-

=Right(Str(Year(Now())),2)

The breakdown of expression 2 is as follows:

NOTE: The right two characters are returned as a text value. If you want them to be returned as a number, use the following expression:

=Year(Now()) Mod 100

REFERENCES

For more information about the first expression, click Microsoft Access Help on the Help menu, type format property - date/time data type in the Office Assistant or the Answer Wizard, and then click Search to view the topic.

For more information about the elements in the second expression, in the Visual Basic Editor, click Microsoft Visual Basic Help on the Help menu, type year function, right function, str function, or now function in the Office Assistant or the Answer Wizard, and then click Search to view the topic.


Top    17A

How to Edit Data in a Hyperlink Field in a Table

SUMMARY

You cannot edit the information in a Hyperlink field in a table by clicking the link because that activates the link. This article describes the different parts of a Hyperlink data type, and shows you several methods that you can use to edit a Hyperlink field.

MORE INFORMATION

Description of the Hyperlink Data Type

You can use Hyperlink fields to store links to other objects in an Access database, links to other files on your hard drive or network, or links to intranet and Internet Web addresses. Each Hyperlink field can store three pieces of information about a link: the DisplayText, the Address, and the SubAddress. These three pieces are separated by number signs (#) and have the following meaning:

DisplayText#Address#SubAddress

NOTE: When you view a Hyperlink field in the Datasheet view of a table or in a bound text box on a form, all you see is the DisplayText portion of the field. If there is no DisplayText, then you see the Address portion of the field; if there is no Address, then you see the SubAddress portion of the field.

Methods for Editing a Hyperlink Field

For Hyperlink fields in a table, you click in the field to activate the link. If you want to edit the DisplayText, Address, or SubAddress portions of a Hyperlink field, use one of the following methods.

Method 1: Use the Edit Hyperlink Dialog Box

  1. Open the table that has the hyperlink in Datasheet view, or open a form based on the table in Form view.

  2. Right-click in the Hyperlink field to display a shortcut menu.

  3. If you want to change only the DisplayText portion of the field, point to Hyperlink on the shortcut menu, and then type in the Display Text box.

    If you want to change the Address or SubAddress portion of the field, click Edit Hyperlink. In the Edit Hyperlink dialog box, type the Address in the Link to File or URL box and type the SubAddress in the Named Location in File (Optional) box. Click OK.

Method 2: Use TAB Key to Move to the Field

  1. Open the table that has the hyperlink in Datasheet view, or open a form based on the table in Form view.

  2. Place the insertion point in a field earlier in the tab order than the Hyperlink field, and then press the TAB key until the pointer moves to the Hyperlink field.

  3. Press the F2 key to see the complete contents of the Hyperlink field, and then edit the field.

Method 3: Click in the Field

This method may require some practice.

  1. Open the table that has the hyperlink in Datasheet view, or open a form based on the table in Form view.

  2. Note that when you position the mouse pointer over a Hyperlink field, the pointer changes to a hand with a pointing finger. If you click when that pointer is displayed, the link is activated.

  3. To edit a hyperlink in a table, position the mouse pointer over the upper or left edge of the Hyperlink field until it resembles a large plus sign (+), and then click.

    To edit a hyperlink bound to a text box on a form, position the mouse pointer over an edge of the Hyperlink field in a way that does not change the pointer to a hand with a pointing finger, and then click.

  4. Press the F2 key to see the complete contents of the Hyperlink field, and then edit the field.

REFERENCES

For more information about using hyperlinks, click Microsoft Access Help on the Help menu, type "Hyperlink data type" in the Office Assistant or the Answer Wizard, and then click Search to view the topics returned.


Top   18A

How to Embed a Bitmap Object in a Report at Run Time

SUMMARY

This article shows you how to use code to embed a bitmap image in a report at run time. The example uses an image control instead of an OLE object frame to store the bitmap.

You can use Visual Basic for Applications code to embed an OLE object into a control on a form at run time. To use this method, however, you have to set the Enabled property of the control to Yes and the Locked property to No. In a report, OLE object controls do not have Enabled or Locked properties. To work around this behavior in reports, you can embed bitmaps and other graphic images in an image control.

MORE INFORMATION

CAUTION: Following the steps in this example will modify the sample database Northwind.mdb. You may want to back up the Northwind.mdb file and perform these steps on a copy of the database.

  1. Open the sample database Northwind.mdb.

  2. Open the Alphabetical List Of Products report in Design view.

  3. Add an image control to the detail section of the report, and set its Name property to Image0.

    NOTE: The image control requires that you associate an image with it when you insert it in a form or report.

  4. In the Insert Picture dialog box select any bitmap (.bmp) file, such as C:\Windows\Circles.bmp.

  5. Set the OnFormat property of the detail section to the following event procedure:

    Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)
       Me!Image0.Picture = "C:\Windows\Circles.bmp"
    End Sub
  6. Save the report and open it in Print Preview to view the bitmap image.

REFERENCES

For more information about the image control, click Microsoft Access Help on the Help menu, type "image controls, creating" in the Office Assistant or the Answer Wizard, and then click Search to view the topic.

For more information about the Format event in reports, click Microsoft Access Help on the Help menu, type "OnFormat property" in the Office Assistant or the Answer Wizard, and then click Search to view the topic.


Top    19A

How to Filter a Report Using a Form's Filter

SUMMARY

This article describes how to create a command button on a filtered form that, when clicked, opens a report and applies the filter that is on the form to the report.


MORE INFORMATION

This example uses the sample database Northwind.mdb. The technique involves creating a new form and a new report. The form uses event procedures to apply a filter and to open the new report. The report uses the Filter property to apply the same filter that is used in the form.

  1. Open the sample database Northwind.mdb.

  2. In the Database window, click Reports under Objects, and then click New.

  3. In the New Report dialog box, click AutoReport: Tabular, select Customers from the Choose the table or query where the object's data comes from list, and click OK.

  4. Close and save the report as rptCustomers.

  5. In the Database window, click Forms under Objects, and then click New.

  6. In the New Report dialog box, click AutoForm: Tabular, select Customers from the Choose the table or query where the object's data comes from list, and click OK.

  7. Close and save the form as frmFilterForm.

  8. Open frmFilterForm in Design view.

  9. Increase the size of the form footer section so that it can hold three command buttons.

  10. Create a command button in the form footer and set its properties as follows:


       Name: cmdOpenReport
       Caption: Open Report
       OnClick: [Event Procedure]
  11. Set the OnClick property of the command button to the following event procedure:


    Private Sub cmdOpenReport_Click()
        If Me.Filter = "" Then
            MsgBox "Apply a filter to the form first."
        Else
            DoCmd.OpenReport "rptCustomers", acViewPreview, , Me.Filter
        End If
    End Sub
  12. Create a second command button in the form footer and set its properties as follows:


       Name: cmdClearFilter
       Caption: Clear Filter
       OnClick: [Event Procedure]
  13. Set the OnClick property of the second command button to the following event procedure:


    Private Sub cmdClearFilter_Click()
        Me.Filter = ""
    End Sub
  14. Create a third command button in the form footer and set its properties as follows:


       Name: cmdClose
       Caption: Close
       OnClick: [Event Procedure]
  15. Set the OnClick property of the third command button to the following event procedure:


    Private Sub cmdClose_Click()
        DoCmd.Close acForm, Me.Form.Name
    End Sub
  16. Set the following properties for the frmFilterForm form:

       OnOpen: [Event Procedure]
       OnClose: [Event Procedure]
  17. Set the OnOpen property of the form to the following event procedure:


    Private Sub Form_Open(Cancel as Integer)
        Me.Filter = ""
    End Sub
  18. Set the OnClose property of the form to the following event procedure:


    Private Sub Form_Close()
        DoCmd.Close acReport, "rptCustomers"
    End Sub
  19. Switch the form to Form view.

  20. On the toolbar, click the Filter By Form button to set a filter, and then click the Apply Filter button to apply the filter.

  21. Click the Open Report button on the form. A report should appear with the same filter that was applied to the form.

REFERENCES

For more information about the Filter property, click Microsoft Access Help on the Help menu, type Filter Property in the Office Assistant or the Answer Wizard, and then click Search to view the topics returned.

For more information about Filter By Form, click Microsoft Access Help on the Help menu, type Modify a filter in the Filter By Form window in a table, query, or form in the Office Assistant or the Answer Wizard, and then click Search to view the topics returned.

For more information about Filter By Selection, click Microsoft Access Help on the Help menu, type Filter records by selecting values in a form or datasheet in the Office Assistant or the Answer Wizard, and then click Search to view the topics returned.


Top    20A

How to FIND a Record Using ADO and Jet OLE DB Provider

 

SUMMARY

This article applies only to a Microsoft Access database (.mdb).

This article demonstrates how to find records in a Microsoft Jet database using ActiveX Data Objects (ADO) and OLE DB.

MORE INFORMATION

What follows are two example procedures. The first, CreateJetDB, creates a new Microsoft Jet database in the root directory of on drive C and populates it with data. The second, CursorLocationTimed, demonstrates using the Find method with a server side cursor and with a client side cursor.

To create these procedures, follow these steps:

  1. Create a new Microsoft Access database.

  2. Create a new module.

  3. On the Tools menu, click References, and make sure the following references are selected:

    Microsoft ActiveX Data Objects 2.1 Library
    Microsoft ADO Ext. 2.1 for DDL and Security

  4. Type the following procedures:


    Sub CreateJetDB()
       Dim cat As New Catalog
       Dim cn As New Connection
       Dim rs As New Recordset
       Dim numrecords As Long
       Dim i As Long
      
       ' Number of sample records to create
       numrecords = 250000
      
       On Error Resume Next
      
       'Delete the sample database if it already exists.
       Kill "c:\findseek.mdb"
       On Error GoTo 0
      
       'Create a new Jet 4.0 database name findseek.mdb
      
       cat.Create "Provider=Microsoft.Jet.OLEDB.4.0;" & _
       "Data Source=c:\findseek.mdb"
      
        'Set the provider, open the database,
       'and create a new table called tblSequential.
      
       cn.Provider = "Microsoft.Jet.OLEDB.4.0"
       cn.Open "Data Source=c:\findseek.mdb"
       cn.Execute "CREATE TABLE tblSequential (col1 long, col2 text(75));"
      
        'Open the new table.
       rs.Open "tblSequential", cn, adOpenDynamic, _
       adLockOptimistic, adCmdTableDirect
      
       Add sample records to the tblSequential table.
       For i = 0 To numrecords
          rs.AddNew
          rs.Fields("col1").Value = i
          rs.Fields("col2").Value = "value_" & i
          rs.Update
          Next i
       rs.Close
      
       'Create a multifield Index on col1 and col2.
       cn.Execute "CREATE INDEX idxSeqInt on tblSequential (col1, col2);"
      
       'Close the connection
       cn.Close

    End Sub

    Sub CursorLocationTimed()

       Dim cn As New Connection
       Dim rs As New Recordset
       Dim i, j As Long
       Dim time As Variant
      
       On Error GoTo ErrHandler
      
       cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" _
       &  "Data Source=c:\findseek.mdb"
      
       ' Specify how ADO should open the recordset:
       ' adUseServer - use the native provider to perform cursor
       ' operations
       ' adUseClient - use the client cursor engine in ADO
       ' NOTE: adUseServer more closely resembles DAO
      
       ' Time opening a recordset and doing 1000 finds (Server cursor
       ' engine)
       '
       rs.CursorLocation = adUseServer
       time = Timer
      
       ' Open the recordset and perform serveral Finds to locate records.
       ' Using the adCmdTableDirect opens a base table against Jet, which
       ' is generally the fastest, most functional way to access tables.
      
       rs.Open "tblSequential", cn, adOpenDynamic, adLockOptimistic, _
       adCmdTableDirect
      
       For i = 0 To 1000
          rs.Find "col1=" & i
       Next i
      
       Debug.Print "Sequential Find + Open (Server) = " & Timer - time
       rs.Close
      
       ' Time opening a recordset and doing 1000 finds (Client cursor
       ' engine)
      
       rs.CursorLocation = adUseClient
       time = Timer
      
       rs.Open "tblSequential", cn, adOpenDynamic, _
       adLockOptimistic, adCmdTableDirect
      
       For i = 0 To 1000
          rs.Find "col1=" & i
       Next i
      
       Debug.Print "Sequential Find + Open (Client) = " & Timer - time
       rs.Close
      
       Exit Sub

    ErrHandler:

       For j = 0 To cn.Errors.Count - 1
          Debug.Print "Conn Err Num : "; cn.Errors(j).Number
          Debug.Print "Conn Err Desc: "; cn.Errors(j).Description
       Next j
      
       Resume Next

    End Sub
  5. To create the sample database, type the following line in the Immediate window, and then press ENTER:


    ?CreateJetDB()
  6. To demonstrate the Find method, type the following line in the Immediate window, and then press ENTER:
    
    ?CursorLocationTimed() 

    You should next see output similar to the following:

    
       Sequential Find + Open (Server) = 0.28125
       Sequential Find + Open (Client) = 5.28125 

    NOTE: The resulting numbers may differ from computer to computer.


 

Top