Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Indexing and Sorting with VBA


A Table is normally created with a Primary Key or Index to arrange the records into certain order to view or process. Primary Key or Index can have one or more fields, in order to make the Key Values Unique, if this is not possible with a single field.

If you open the Employees Table from C:\Program Files\Microsoft Office\Office11\Samples\Northwind.mdb sample Database in design view you can see that the EmployeeID Field is defined as Primary Key.

To create an Index manually and to define it as Primary Key:

  1. Open the Table in design View.
  2. Click at the left side of the Field Name to select it.
  3. Click on the Indexes Toolbar Button.
  4. You may give any suitable name in the Index Name Field replacing PrimaryKey, if you would like to do so.

If the Record Values in the selected field are not unique then you can select more data fields (up to a maximum of ten Fields) to form Unique Key for the Primary Key.

You may click and drag over the Fields to select them (if they are adjoining fields) or click on each field by holding the Ctrl Key to select fields randomly.

The above procedure is for creating a PrimaryKey Index for the Table. We can create more than one Index for a Table. But, only one Index can be active at one time.

Creating Index with VBA

We can activate an existing Index of a Table or create new Index through VBA and use it for data processing. We will learn here how to create a new Index with the name myIndex for a Table through VBA, activate it and use it for data processing and delete it at the end of the process.

We must validate the presence of myIndex in the Indexes collection of the Table, if found then activate it, otherwise create myIndex and activate it for data processing.

We will use Orders and Order details Table from Northwind.mdb sample database. We will organize the Order Details Table in Order Number sequence so that Order-wise Total Value of all items can be calculated and updated on the same Order record in Orders Table.

The Data Processing Steps

Following are the data processing steps which we follow in the VBA Routine to update the Orders Table with order-wise Total Value from Order details Table:

  1. Open Orders Table for Update Mode.
  2. Open Orders Details Table for Input.
  3. Check for the presence of myIndex in the Order Details Table, if found then activate it, otherwise create myIndex and activate it as current Index.
  4. Initialize Total to Zero.
  5. Read the first record from the Order details Table.
  6. Calculate Total Value of the item using the Expression: Quantity * ((1-Discount%)*UnitPrice).
  7. Add the Value to the Total.
  8. Read the next record and compare with the earlier Order Number, if same then repeat step-6 and 7 until the Order Number changes or no more records to process from Order Details Table.
  9. Find the record with the Order Number in Orders Table.
  10. If found then edit and updateTotal into the TotalValue Field in Orders Table.
  11. Check for End Of File (EOF) condition of Order Details Table.
  12. If False then repeat the Process from Step-4 onwards, otherwise Close files and stop Run.

Prepare for a Trial Run.

  1. To try the above method Import Orders and Order Details Tables from C:\Program Files\Microsoft Office\Office11\Samples\Northwind.mdb (Access 2003) or C:\Users\User\My documents\Northwind 2007.accdb (Access 2007, if not available then you must create from Local Templates)
  2. Open Orders Table in Design View.
  3. Add a new Field with the name TotalValue with Numeric (Double) data Type in Orders Table.

    You may display the Index List of this Table to view its PrimaryKey Index on Order ID field.

  4. Save the Orders Table.
  5. Open the VBA Editing Window (Alt+F11).
  6. Create a new Standard Module from Insert Menu.
  7. Copy and Paste the following VBA Routine and save the Module.

    Create Index Function.

    Public Function CreateIndex()
    Dim db As Database, fld As Field, tbldef As TableDef
    Dim idx As Index, rst As Recordset, PreviousOrderID As Long
    Dim CurrentOrderID As LongDim xQuantity As Long, xUnitPrice As Double
    Dim xDiscount As Double, Total As Double, rst2 As Recordset
    On Error Resume Next
    Set db = CurrentDb
    Set rst = db.OpenRecordset("Order Details", dbOpenTable)
    'Check for presence of myIndex, if found set as current
    rst.Index = "myIndex"
    If Err = 3800 Then
    'myIndex not found
        GoSub myNewIndex
    End If
    On Error GoTo CreateIndex_Err
    Set rst2 = db.OpenRecordset("Orders", dbOpenTable)
    rst2.Index = "PrimaryKey"
    PreviousOrderID = rst![Order ID]
    CurrentOrderID = PreviousOrderID
    Do Until rst.EOF
        Total = 0
        Do While CurrentOrderID = PreviousOrderID
            xQuantity = rst![quantity]
            xUnitPrice = rst![unit price]
            xDiscount = rst![discount]
            Total = Total + (xQuantity * ((1 - xDiscount) * xUnitPrice))
            PreviousOrderID = CurrentOrderID
            If Not rst.EOF Then
                CurrentOrderID = rst![Order ID]
                Exit Do
            End If
        rst2.Seek "=", PreviousOrderID
        If Not rst2.NoMatch Then
            rst2![totalvalue] = Total
        End If
        PreviousOrderID = CurrentOrderID
    'Delete temporary Index
    Set tbldef = db.TableDefs("Order details")
    tbldef.Indexes.Delete "myIndex"
    Exit Function
    Set tbldef = db.TableDefs("Order Details")
    Set idx = tbldef.CreateIndex("myIndex")
    Set fld = tbldef.CreateField("Order ID", dbLong)
    idx.Fields.Append fld
    Set fld = tbldef.CreateField("Product ID", dbLong)
    idx.Fields.Append fld
    tbldef.Indexes.Append idx
    Set rst = db.OpenRecordset("Order Details", dbOpenTable)
    rst.Index = "myIndex"
    MsgBox Err.Description, , "CreateIndex()"
    Resume CreateIndex_Exit
    End Function
  8. Click somewhere in the middle of the VBA Routine and press F5 or click Run Command Button to execute the Code and update the Orders Table.

At the beginning part of the Code we are attempting to make one of the Indexes (myIndex) of Order Details Table active. Since, myIndex is not yet created on the Table this action runs into an Error condition. we are trapping this Error Code and passes control to the Sub-Routine to create myIndex and to add it to the Indexes collection. The new Index is activated in preparation for data processing.

Next steps calculate Order-wise Total Values and updates on Orders Table.

At the end of the process myIndex is deleted from the Indexes Collection of Order Details Table.


No comments:

Post a Comment

Comments are subject to moderation before publishing.


Subscribe in a reader
Your email address:

Delivered by FeedBurner

Blog Directory Visit blogadda.com to discover Indian blogs


Popular Posts

Search This Blog

Blog Archive

Powered by Blogger.

Follow by Email


Forms Functions How Tos MS-Access Security Reports msaccess forms Animations msaccess animation Class Module Utilities msaccess controls Access and Internet MS-Access Scurity MS-Access and Internet Array Queries msaccess reports External Links msaccess tips Accesstips Downloads Objects Property Menus and Toolbars Controls Event MsaccessLinks Process Controls Art Work Collection Object WithEvents msaccess How Tos Combo Boxes Graph Charts List Boxes VBA msaccessQuery Command Buttons Command Button Data Dictionary Object Emails and Alerts Form Query RaiseEvent Report Calculation Custom Wizards DOS Commands Data Type ms-access functions msaccess functions msaccess graphs msaccess reporttricks Custom Functions Item Object Reference msaccessprocess security advanced Access Security Add Field Type Fields Form Instances Key Macros Menus SubForm Top Values Variables msaccess email msaccess menus progressmeter Access2007 Auto-Number Copy Excel Expression Join Methods Microsoft Numbering System Records Recordset Security Split Table Time Difference Utility Workgroup Wrapper Classes database function ms-access msaccess wizards reference text tutorial vba code Access2003 Accounting Year Action Animation Attachment Binary Numbers Bookmarks Budgeting ChDir Color Palette Conditional Formatting Data Filtering Defining Pages Diagram Disk Dynamic Lookup Error Handler Export External Filter Formatting Groups Hexadecimal Numbers Import Labels List Logo Macro Mail Merge Main Form Memo Monitoring Octal Numbers Operating System Paste Primary-Key Product Rank Reading Remove Rich Text Sequence SetFocus Summary Tab-Page Tables Union Query User Users Water-Mark Word automatically commands hyperlinks iSeries Date iif msaccess msaccess alerts pdf files restore switch toolbar updating upload

Featured Post

ROUNDDOWN Function of Excel

We have introduced ROUNDUP() Function of Excel in Microsoft Access earlier.  It works like ROUND() Function except that the number is alway...


Blog Archive

Recent Posts