Microsoft Access VBA Tutorials for self-paced learning, Class Modules, SQL Techniques, and AI Integration Guides.

Data Change Monitoring

Introduction

In a secure environment—databases implemented with Microsoft Access Security—several options are available to protect data from unauthorized changes. With User-level security, you can clearly define who can modify data, view data, or which group of users is restricted from opening a particular form. Unfortunately, these features are not available in Microsoft Access 2007 and later versions, which is surprising given their usefulness.

Regardless of whether a database is secured or not, data integrity remains crucial. Let us highlight a small issue that can arise during data editing or viewing.

Suppose a user needs to search for certain records on a form and update specific field values—for example, a customer’s telephone number, fax number, or other details. When the user moves from one record to another, Access should ideally prompt for confirmation if any changes were made to the record before saving.

There are two common approaches to handling this:

  1. Overall Record Check (Simple Method):
    This method checks the Dirty status of the form to determine if any changes were made to the current record. It does not detect which specific fields were modified, only that changes exist. The system can then prompt the user with a warning: if the user agrees, the changes are saved; otherwise, the update is canceled.

  2. Field-Level Change Tracking (Advanced Method):
    This method tracks changes made to each individual field in the record. Before updating, it presents the modifications to the user. The record is updated only if the user confirms; otherwise, the changes are canceled. This method provides more granular control and is highly effective in maintaining data accuracy.

Try the first method on a form.

  1. Open one of your databases with a Data Editing Form.

  2. Open an existing Form in Design View.

  3. Display the VBA Module of the Form.

  4. Copy and paste the following code into the VBA Module of the Form (you can use this code in any form):

    Private Sub Form_BeforeUpdate(Cancel As Integer)
    Dim msg As String
    
    On Error GoTo Form_BeforeUpdate_Err
    
      If Me.Dirty And Not Me.NewRecord Then
         msg = "Update the changes on Record." & vbCr & vbCr & "Proceed...?"
         If MsgBox(msg, vbYesNo + vbDefaultButton2 + vbQuestion, "Updating Changes") = vbNo Then
             Me.Undo
         End If
      End If
    
    Form_BeforeUpdate_Exit:
    Exit Sub
    
    Form_BeforeUpdate_Err:
    MsgBox Err & " : " & Err.Description, , "Form_BeforeUpdate()"
    Resume Form_BeforeUpdate_Exit:
    End Sub
  5. Save the form and open it in Normal View.

  6. Make some changes to one or two fields of the current record.

  7. Press Ctrl+S to update the changes.

The following message box will pop up:

If the user selects Yes, the changes are saved to the record. If the user selects No, the old values are restored.

In this method, the user must be vigilant about the changes they make to the record. Microsoft Access does not provide any indication of what was changed or which specific fields were modified.

A Different Approach.

The second method tracks changes in each field and shows them to the user.  The following steps we have followed to implement this method:

  1. In the Form_Load() Event Procedure, the structure of the record set attached to the Form is scanned for Field Names and Data Types.

    • Field Names and Data Types are loaded into two similar Variant Arrays (Rec() and Rec2(), both are two-dimensional arrays), leaving one element of the Array for loading Field Values later.

    • The memo, OLE Object, Hyperlinks, and Attachment fields are exempted from validation checks.

  2. In the Form_Current() event procedure, the current record’s field values—excluding Memo, OLE Object, Hyperlink, and Attachment fields—are loaded into the Rec() array. If the user creates a new record, these values are not loaded or checked. After this step, the user may make changes to the record.

  3. In the Before_Update() event procedure, the current record’s field values are loaded into a second array Rec2() and compared with the values stored earlier in the Rec() array. If any field values differ, it is assumed that the user has made changes to those fields. The Field Name, Old Value, and New Value for each changed field are formatted into a message and displayed to the user. A sample image of this message is shown below:

  4. At this point, the user can review the changes and reconfirm them before updating the record by selecting Yes in the message box, or choose No to cancel the changes and restore the original values.

You may copy and paste the following code into the VBA Module of any data editing Form and try it out as we did earlier:

The Form's Class Module VBA Code.

Option Compare Database
Option Explicit

Dim Rec() As Variant, Rec2() As Variant, j As Integer
Dim rst As Recordset, fld_count As Integer, i As Integer


Private Sub Form_BeforeUpdate(Cancel As Integer)
'-----------------------------------------------------
'Author : a.p.r.pillai
'Date   : May 2011
'Remarks: All Rights Reserved by www.msaccesstips.com
'-----------------------------------------------------
Dim msg As String

On Error GoTo Form_BeforeUpdate_Err

If Me.Dirty And Not Me.NewRecord Then
   'Load Field Values after changes into the second array
   For i = 0 To fld_count
       If Rec(i, 0) <> "xx" Then
         Rec2(i, 1) = Me.Controls(Rec(i, 0)).Value
       End If
   Next
   
   'Identify fields with changes made
   'and Mark them.
   For i = 0 To fld_count
     If Rec(i, 0) <> "xx" Then  'If Memo/OLE Object/Hyperlink/Attachment field then skip
        If Rec(i, 1) = Rec2(i, 1) Then
           Rec2(i, 2) = False
        Else
           Rec2(i, 2) = True
        End If
     End If
   Next

   msg = ""
   'Take changed field values and format a message string
   For i = 0 To fld_count
      If Rec2(i, 2) = True And Rec(i, 0) <> "xx" Then
         msg = msg & "[" & UCase(Rec(i, 0)) & "]" & vbCr
         msg = msg & "       Old:  " & Rec(i, 1) & vbCr
         msg = msg & "      New:  " & Rec2(i, 1) & vbCr & vbCr
      End If
   Next
   'If not approved by User reverse the change.
   If Len(msg) > 0 Then
      msg = msg & vbCr & "Update the changes..?"
      If MsgBox(msg, vbYesNo + vbDefaultButton2 + vbQuestion, "Update Change") = vbNo Then
           Me.Undo
      End If
   End If
End If

Form_BeforeUpdate_Exit:
Exit Sub

Form_BeforeUpdate_Err:
MsgBox Err & " : " & Err.Description, , "Form_BeforeUpdate()"
Resume Form_BeforeUpdate_Exit

End Sub

Private Sub Form_Current()
'-----------------------------------------------------
'Author : a.p.r.pillai
'Date   : May 2011
'Remarks: All Rights Reserved by www.msaccesstips.com
'-----------------------------------------------------

On Error GoTo Form_Current_Err
'Load the current record value into array
'Before change
For i = 0 To fld_count
    If Rec(i, 0) <> "xx" Then
        Rec(i, 1) = Me.Controls(Rec(i, 0)).Value
    End If
Next

Form_Current_Exit:
Exit Sub

Form_Current_Err:
MsgBox Err & " : " & Err.Description, , "Form_Current()"
Resume Form_Current_Exit

End Sub

Private Sub Form_Load()
'-----------------------------------------------------
'Author : a.p.r.pillai
'Date   : May 2011
'Remarks: All Rights Reserved by www.msaccesstips.com
'-----------------------------------------------------

On Error GoTo Form_Load_Err
Set rst = Me.RecordsetClone
fld_count = rst.Fields.Count - 1

'Redimension the array for Number of fields
ReDim Rec(0 To fld_count, 0 To 2) As Variant
ReDim Rec2(0 To fld_count, 0 To 3) As Variant
'Load field Name and Type into array
'Memo Field type is 12 and will be excluded
'from validation checks
For i = 0 To fld_count
   j = rst.Fields(i).Type
   If j <> 11 And j <> 12 And j <> 101 Then
       Rec(i, 0) = rst.Fields(i).Name
       Rec2(i, 0) = Rec(i, 0)
       Rec2(i, 3) = rst.Fields(i).Type
   Else
       Rec(i, 0) = "xx"
   End If
Next

Form_Load_Exit:
Exit Sub

Form_Load_Err:
MsgBox Err & " : " & Err.Description, , "Form_Load()"
Resume Form_Load_Exit
End Sub

The Code is not extensively tested for logical errors. Use it at your own risk.

Share:

Continued on Page 2 on Report

Introduction

Normally, MS-Access reports can span several pages, and it is often useful to display the current page number along with the total number of pages. To achieve this, a TextBox is added to the Page Footer section of the report. In the Control Source property of this TextBox, you can enter an expression like the following:

=”Page: “ & [page] & “ of “ & [pages]

Result: Page 1 of 15

OR

="Page: " & [page] & " / " & [pages]

Result: Page: 1 / 15

Report Date is also added in the page footer area like ="Date: " & format(date(), ”dd/mm/yyyy”)

We often find ourselves repeatedly writing these expressions whenever a new report is designed. If you are a VBA enthusiast, you can automate this process by creating small, reusable User-Defined Functions (UDFs) in your application. By calling the function from a Text Box’s Control Source property, you can quickly insert the required information into your report. I have created two such functions for this purpose—if you’d like to take a look at them, click here.

This approach is especially efficient for developers aiming to standardize functionality across multiple Access applications, much like the concept discussed in your blog post on the MS-Access Reference Library.

Returning to the topic of the page indicator, we aim to display page continuity information in the Report’s Page Footer, but with a slight variation. A report may consist of a single page or multiple pages. When the report spans more than one page, the footer on the first page should display: “Continued on Page 2.”

On subsequent pages (page 2, page 3, etc.), the label should update accordingly—for example, “Continued on Page 3”, and so on—up to the second-to-last page. This label should not appear on the final page. If the report consists of only a single page, the label should be omitted entirely.

Using the first example at the beginning of this article, a single-page report will simply print as “Page 1 of 1.”

Try out the Page Footer Setting

  1. To try our new page labels, open one of your Reports with a few pages.

  2. Create a Text Box, wide enough to display the label, like Continued on Page 99, at the Page Footer of the Report.

  3. Write the following expression in the Control Source Property of the Text Box.

  4. =IIf([Pages]>1 And [Page]<[Pages],"Continued on Page " & [Page]+1,"")

  5. Save the Report and open it in Print Preview.

  6. Check the last page of the Report.  This label should not appear there.

  7. Try this out on a single-page Report.

NB: [page], [pages] are System Variables and they should be used in the expression without change. &hypen;

Earlier Post Link References:

Share:

Product Group Sequence with Auto Numbers

Introduction.

How to generate automatic sequence numbers for different Categories of Products in a Form.  See the sample data given below to understand the gravity of the problem more clearly:

CatCod Category ProdSeq Product Description
1 Beverages 1 Coffee
1 Beverages 2 Tea
1 Beverages 3 Pepsi
2 Condiments 1 Aniseed Syrup
2 Condiments 2 Northwoods Cranberry Sauce
2 Condiments 3 Genen Shouyu
2 Condiments 4 Vegie-spread
3 Confections 1 Uncle Bob's Organic Dried Pears
3 Confections 2 Tofu
1 Beverages 4  
2 Condiments 5  

The first two columns represent the Product Category Code and its Description, respectively. The third column contains the Category-wise Product Sequence Numbers, and the fourth column lists the Product Description. The product serial number is consecutive. The combination of Category Code and Product Sequence Number forms the Primary Key of the table, so duplicate Product Sequence Numbers are not allowed.

The Product file contains multiple products under each category (e.g., 1. Beverages, 2. Condiments, etc.), and each product within a category should have its own unique sequence number. Product sequence numbers must not contain duplicates.

When a new product is added to a category, the form should automatically generate the next sequence number. Manually tracking the last sequence number used for each category during data entry is impractical. However, MS Access can handle this task efficiently and accurately. A simple VBA routine on the form can accomplish this automatically.

An image of a sample Form for the above data is given below:

The first field, Category Code (1, 2, 3, etc.), is a lookup field implemented as a combo box linked to the Category Table. On the property sheet, the first column width is set to 0 so that the category description is displayed in the combo box instead of the numeric code.

During data entry, the user first selects a Product Category in the initial field to prepare for adding a new product under that category. When the user presses the Tab key to move out of the Category field, the next sequence number (i.e., the existing Product Sequence Number + 1) is automatically inserted into the ProdSeq field. The user then needs to enter only the Product Description manually. The ProdSeq field can be locked to prevent accidental changes.

The following program runs in the Category_LostFocus() event procedure. It identifies the highest existing Product Sequence Number for the selected category, calculates the next sequence number, and automatically inserts it into the ProdSeq field:

The Category LostFocus Code.

Private Sub Category_LostFocus()
Dim i, s
If Me.NewRecord Then
     i = Me!Category
     s = Nz(DMax("ProdSeq", "Products", "Category = " & i), 0)
     s = s + 1
     Me![ProdSeq] = s
End If 
End Sub

The program works only when the user attempts to create a New Record.

If the Category Code is a Text value, then you need to make a change in the criteria part of the DMax() Function as given below:

s = Nz(DMax("ProdSeq", "Products", "Category = ‘" & i & "’"), 0)
Technorati Tags:
Share:

Invoke Word Mail Merge from Access2007

Introduction

Mail Merge is a powerful feature that is used to create and print form letters in the Microsoft Word Application. For example, employment contracts often contain fixed terms but require variable details, such as the employee's name, address, basic pay, allowances, and contract period. Traditionally, these documents were preprinted with standard terms and included blank spaces or dotted lines where personal details were filled in manually or with a typewriter. With Mail Merge, however, the document can be printed in its complete form, with personal details automatically inserted into the appropriate locations alongside the standard contract terms. This process can be automated and generated for multiple employees within minutes.

All that’s required is to create a table containing employees’ personal details, design a single Mail Merge Word document with the standard terms of the employment contract, link the Access table to the Word document, and insert the personal detail fields wherever needed. Once set up, the document can be merged and printed directly to the printer.

In MS Access 2007, part of this mail merge process can be initiated directly by selecting a table or query to link with the Mail Merge document in Microsoft Word. You can either connect the table/query to an existing Word document or create a new document linked to the selected data source. Let us create a sample document to see how this works in Microsoft Access 2007.

Prepare for a Demo Run.

  1. Open Microsoft Access 2007.

  2. Open the sample database Northwind2007.accdb, or import the Employees table from this database into any database that you wish to open to try this out.

  3. Click on the Employees Table in the navigation pane to select it.

  4. Select External Data -> Export -> More -> Merge it with Microsoft Word.

    Microsoft Word Mail Merge Wizard opens up and gives you two choices: either to open an existing Word document or to create a new one and link the Employees Table with the document. 

    Depending on what option you have selected, the Employee Table is linked to that document.

  5. Select the Word Menu Mailings -> Insert Merge Fields to display the linked Employees Table field list. See the image given below.

  6. Now, you must place the attached Table's data fields in appropriate locations on the Document's body to insert their contents there.  I have placed the name and address of the attached Employees Table on the Document.  The sample Document image is given below:

  7. Place the insertion point where you want the field content to appear, then select the field from the Mailings -> Insert Merge Fields Menu.

  8. Repeat this action to place other fields in appropriate places in the document.

  9. You can preview the Document by selecting Mailings -> Preview Results at any preparation stage of the document.  The sample preview of the above test fields is given below:

If the Employees table has 50 records, then 50 copies of this Document will be printed when you select the option Mailings -> Finish & Merge -> Print Documents; i.e., one document for each employee with their respective personal details merged in.

Technorati Tags:
Share:

Copy Paste Data from Excel to Access2007

Introduction.

Microsoft Office Applications already provide built-in methods to transfer data between them. This can be implemented by importing or exporting data, directly linking to the source while keeping the original data intact in the parent application, or by simply copying data to the clipboard and pasting it into another program. These options have long been available.

In earlier versions of Access, you first needed to create a table with matching field types before pasting or appending data. Access 2007 has made this process much simpler. For example, you no longer need to create a table beforehand when pasting data from Excel. Instead, Access 2007 prompts you to confirm whether the copied data includes header rows. If you select Yes, Access automatically creates a new table (using the worksheet name) and pastes the data into it, assigning the correct field types.

Let us find out how?

  1. Open Microsoft Excel and create a small database with the sample data given below:

  2. Open Microsoft Access 2007 and open an existing .accdb database or create a new one.

  3. Make the Excel database window active.

  4. Highlight the Excel database range, including the header row.

  5. Select Copy from the Home Menu, to transfer the data into the Clipboard.

  6. Make the Access 2007 database window active.

  7. Right-click on the Navigation Pane of Tables and select Paste from the shortcut menu.  The following message box is displayed:

  8. If you have included the header line of the data while coping it, then you may click on the Yes Command Button; otherwise, select No.

A new Table will be created with the Worksheet name.  The header cell values will be used as field names.  The field data type (Text, Date, Number, etc.) will be correctly defined depending on the data type that you have copied from Excel.

If you have selected No, then the data will still be pasted into a new table, but the field names will be F1, F2, F3, etc.

Technorati Tags:
  1. Roundup Excel Function in MS-Access
  2. Proper Excel Function in Microsoft Access
  3. Appending Data from Excel to Access
  4. Writing Excel Data Directly into Access
  5. Printing MS-Access Report from Excel
  6. Copy-Paste Data From Excel to Access 2007
  7. Microsoft Excel-Power in MS-Access
  8. Rounding Function MROUND of Excel
  9. MS-Access Live Data in Excel
  10. Access Live Data in Excel- 2
  11. Opening an Excel Database Directly
  12. Create Excel, Word Files from Access
Share:

User-level Access Security and Access2007

Introduction.

In versions of Microsoft Access before Access 2007, User-level and Object-level Security were reliable methods for protecting applications. I secured all my Access applications with User- and Group-level security, which proved highly effective when the applications were shared over a network. Because of this, I never needed to lock VBA modules with a password or convert the applications into a compiled form (MDE format) to prevent tampering. User-level security provided sufficient control to assign users precisely the level of access intended for them within the application.

If you wish to continue using this feature in Access 2007, you must avoid converting earlier databases (with the .mdb extension) to the newer .accdb format. Once converted, all User-level security settings are removed and cannot be reinstated. However, you can still maintain and use User-level security in Access 2007 as long as your databases remain in Access 2003 or earlier formats (with the .mdb extension).

Database Objects and Permissions

With User-level Security, you can control what users can do and what they should not do.  Check the following table to get some idea as to how to set permissions on each object type and what they do:

Permission Applies to these objects Result
Open/Run Entire database, forms, reports, macros Users can open or run the object, including procedures in code modules.
Open Exclusive Entire database Users can open a Database and lock out other users.
Read Design Tables, queries, forms, macros, code modules Users can open the listed objects in the Design view. Note: Whenever you grant access to the data in a table or query by assigning another permission, such as Read Data or Update Data, you also grant Read Design permissions because the design must be visible to correctly present and view the data.
Modify Design Tables, queries, forms, macros, code modules Users can change the design of the listed objects.
Administer The entire database, tables, queries, forms, macros, and code modules Users can assign permissions to the listed objects, even when the user or group does not own the object.
Read Data Tables, queries Users can read the data in a table or query. To grant user permissions to read queries, you must also give those user permissions to read the parent tables or queries. This setting implies Read Design permission, which means that users can read your table or query design in addition to the data.
Update Data Tables, queries Users can update the data in a table or query. Users must have permission to update the parent table or queries. This setting implies both Read Design and Read Data permissions.
Insert Data Tables, queries Users can insert data into a table or query. For queries, users must have permission to insert data into the parent tables or queries. This setting implies both Read Data and Read Design permissions.
Delete Data Tables, queries Users can delete data from a table or query. For queries, users must have permission to delete data from the parent Tables or Queries. This setting implies both Read Data and Read Design permissions.
Technorati Tags:

Earlier Post Link References:

Share:

Macros and Temporary Variables

Introduction.

If you are using Microsoft Access 2007 or a later version, there is a useful new feature: the SetTempVar action in Macros, which allows you to define global variables. Once defined, these variables can be used across other macros, event procedures, forms, or reports. The temporary variables remain in memory until you explicitly clear them using the RemoveTempVar action (for a single variable) or the RemoveAllTempVars action (to clear all). All temporary variables are automatically removed from memory when you close the database.

The TempVar Usage in Macros.

Let us try a quick example to understand the usage in macro:

  1. Select Macros from the Create Menu.

  2. Select SetTempVar Action in the first row.

  3. Type myName in the Name argument.

  4. Type the expression Inputbox(“Type your Name”) in the expression argument.

  5. Save the Macro with a name (say macDefineVar).

  6. Right-click on the macro and select Run from the shortcut menu (or Double-click) to execute the Macro.  The InputBox Function will run and prompt for a value to type.

  7. Type your name and click the OK Command Button.

    Your name is stored in the Variable myName. We have used the Function, InputBox() in the expression argument.  You can use constant values, functions, or expressions to assign values to the variable myName.

  8. Open a new form in the design view.

  9. Insert a Text Box in the details section of the Form.

  10. Type the expression =Tempvars!myName in the Control Source property.

  11. Change the form from Design view to Form View.

    Your name will now appear in the text box. The above example demonstrates how to define a temporary variable and reference it in expressions on a form. Next, let us see how to remove this variable from memory.

  12. Close the Form.

  13. Select Macro from the Create menu to open up a new macro in the design view.

  14. Select RemoveTempvar from the Action list.

  15. Type myName in the Name parameter.

  16. Save the macro with the name macRemoveVar.

  17. Double-click on the macRemoveVar macro to execute it.

  18. Open the form again to check whether your name still appears in the text box on the form or not.

The text box will be empty, indicating that the variable myName does not exist in memory.  The RemoveTempvar action needs a variable name as a parameter.

TempVar Usage in Query.

Let us take this a step further and build something more practical for real-world scenarios. This time, we will calculate the order-wise percentage based on the total Order quantity. We explored a similar problem earlier in the blog post Percentage in Total_Query.

The key requirement here is to obtain the sum of all order quantities to calculate the percentage for each individual order. In the earlier example, we accomplished this by creating a separate query to calculate the total order quantity and then linking it with a second query, grouped by Order Number, to compute the percentages.

Here we will initialize a Temporary Variable with the sum of Quantity and use the Variable name in the percentage calculation expression.

  1. Import the Order Details table from the Northwind sample database.

  2. Select Query Design from the Create menu; don't select any table or query from the displayed list.

  3. Change the Query in SQL view; copy and paste the following SQL string and save the Query with the name OrderPercentageQ:

    SELECT [Order Details].OrderID, First([Order Details].UnitPrice) AS UnitPrice, Sum([Order Details].Quantity) AS Quantity
    FROM [Order Details]
    GROUP BY [Order Details].OrderID;
    
  4. Open the macro macDefineVar in the design view.

  5. Change the variable name, myName, to TotalQuantity (myName variable will remain in memory).

  6. Change the expression InputBox(“Enter your Name”) to DSum(“Quantity”,”[Order Details]”).  Do not add the = symbol at the beginning of the expression.  Save the macro with the change.

  7. Double-click on the macro to run and calculate the total quantity and store the value in the temporary variable TotalQuantity.

    We will modify the OrderPercentageQ with the addition of a new column that calculates the order-wise percentage of total orders.

  8. Open a new Query in SQL View.

  9. Copy and paste the following SQL String into the SQL editing window of the new Query and save it with the name OrderPercentageQ2:

    SELECT [Order Details].OrderID, First([Order Details].UnitPrice) AS UnitPrice, Sum([Order Details].Quantity) AS Qty, Sum([quantity])/[tempvars]![totalQuantity]*100 AS Percentage
    FROM [Order Details]
    GROUP BY [Order Details].OrderID;
    
  10. Open the Query in Design View and check how we have written the expression in the last column to calculate the percentage using the temporary variable [tempvars]![totalQuantity].

  11. Change the Query View into Datasheet View to display the Order-wise percentage of Total Quantity.

The TempVar Usage in VBA.

We can work with the Temporary Variable (Tempvars Object) in VBA.

With the Add method, we can define a Temporary Variable and assign an initial value to it.

Add() method of TempVars Object:

    Syntax: TempVars.Add "Variable Name", "Initial Value"

    Example-1: TempVars.Add "TotalQuantity", DSum("Quantity", "[Order Details]")

    OR

    Example-2: TempVars!TotalQuantity =  DSum("Quantity", "[Order Details]")

You can define a total of 255 temporary variables in this way. 

Remove method of TempVars Object:

The Remove() method erases only one variable and frees the memory occupied by the variable.

    Syntax: TempVars.Remove "Variable Name"

    Example: TempVars.Remove "TotalQuantity"

RemoveAll method of TempVars Object:

The RemoveAll() method removes all the temporary variables defined with the Add() method.

    Syntax: TempVars.RemoveAll

    Example: TempVars.RemoveAll

The Count property gives the count of all temporary variables defined in memory:

Example: Debug.Print TempVars.Count returns the count of temporary variables defined in memory

TempVars Item Indexes.

Each temporary variable stored in memory is assigned an index number, starting from 0 up to (total number of variables – 1). A variable can be referenced by its Item index, which allows you to read its Name or Value, or even assign a new value to it. The Debug.Print TempVars.Item(0).Name prints the name of the variable.

SumofQuantity = TempVars.Item(0).Value

You can also use this reference to modify the existing value in the temporary variable.

TempVars.Item(0).Value = TempVars.Item(0).Value + 1

You should not use a subscript beyond the existing number of temporary variables in memory; otherwise, an error will occur.  If you have defined 5 variables, then the valid index numbers are 0 to 4.

Earlier Post Link References:

Share:

Easy-Read Reports

Introduction.

When computer reports, accounting ledger statements, or purchase invoices are printed with closely spaced lines, readability improves if alternate lines are shaded with a light background color. Traditionally, pre-printed stationery was used for this purpose. Line printers typically print six lines of data within a one-inch vertical space. To emphasize headlines, the double-strike method was used, where the hammer struck each character twice—this being the only enhanced printing style available in line printers.

Line-printer-based reports were designed on graph-paper-like sheets, with carefully written code to position headings, data lines, and summaries precisely on the pre-printed stationery.

An A4 sheet (8.5 × 11 inches) provides 66 print lines vertically. Of these, one inch at the top and half an inch at the bottom are reserved as margins, while the alternate data lines are shaded in green—similar to the sample image shown below.

A4-size paper has 80 print positions across when a 10-character-per-inch (pitch) font size is used. This can be increased to 96 characters if a 12-character-per-inch character size is used.

The above details provide a general background about computer stationery. Reports designed for line printers were created with these specifications in mind. When necessary, you can design reports for plain paper by setting the section height and the text box control height to one-sixth of an inch, matching the line spacing used by traditional line printers.

Light Shading of Alternate Report Data Lines

We will use a simple trick to print alternate lines with a shaded background, making the report easier to read. There is no need for pre-printed stationery, as the shading will be applied dynamically during printing.

You can design a Quick Report and add a few lines of VBA code in the report’s class module. If you already have a report with closely spaced detail lines, you may skip directly to step 3 below.

  1. Import Products Table from MS-Access sample database Northwind.mdb

  2. Use the Report Wizard to design a Tabular Report with the Products Table, like the sample image given below:

  3. Open the Report in Design View.

  4. Select all the controls on the Detail Section of the Report and drag them to the right to get enough space to draw a Text Box on the left side to display Serial Numbers on the Report Lines.  Drag the heading lines and position them to the right.

  5. Draw a Text Box on the left side and write the expression =1 in the Control Source Property.  Change the Name Property Value to SRL.

  6. Change the Running Sum Property Value to Over All.

  7. Create a Label control at the Page Header above the Text Box and change the Caption to SRL (for Serial Number).

  8. Select all the controls in the Detail Section together and display the Property Sheet (F4 or Alt+Enter).

  9. Change the Top Property Value to 0.  All the controls will be shifted and positioned at the top edge of the Detail Section.

  10. Select the Rectangle Tool from the Toolbox and draw a rectangle around all the text boxes in the Detail Section (see the design view image above).

  11. Display the Property Sheet of Rectangle (F4) and change the Name Property Value to Box1.

  12. Select the Send-to-Back option from the Arrange Menu to position the rectangle behind the text box controls.

  13. Reduce the Detail Section height so that there is no empty space below the TextBox controls.

  14. Display the VBA Code Module of the Report (ALT+F11).

  15. Copy and paste the following lines of VBA Code into the Code Module and save the Report:

    The Report Module VBA Code.

    Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)
    Dim xSrl
    xSrl = [SRL]
    If xSrl / 2 = Int(xSrl / 2) Then
       [Box1].BackColor = &HCCC8C2
    Else
       [Box1].BackColor = &HFFFFFF
    End If
    End Sub
    
  16. Open the report in Print Preview.  You will find the result as shown in the report image at the top of this page.

Share:

Top N Records in Query

Top N Records in Query.

We have seen the usage of different types of complicated Queries like the following:

Today, we will learn how to define and extract the top 100 records, or a certain percentage of the total records, based on the values in a particular Column.

Review of Rules of Queries.

You need to know only a few rules to work with this type of Query.

  1. You can select several Columns of data from the source for output.

  2. You must sort one or more columns of data in ascending or descending Order, and the leftmost sorted column will pick the top valuation records.

  3. If the output contains duplicate records (i.e., two or more records with identical values in all columns), you can set the Unique Values property to Yes, which is equivalent to using a DISTINCT clause in the SQL SELECT statement, to suppress the duplicates.

  4. If the query has more than one Table/Query as the source, and duplicate records are found in the output, set the Unique Records Property to Yes (DISTINCTROW clause in the SELECT statement) to suppress duplicates.

Create a Sample Query.

  1. Create a new database or one of your existing databases.

  2. Import the Order Details and Products Table from the Northwind.mdb sample Database. There is a Combobox in the Order Details Table that retrieves the Product Name from the Products Table. The Product Code in the Order Details Table is linked to the Product Code in the Products Table. Open a new Query in SQL View (without selecting a Table/Query from the displayed list).

  3. Copy and paste the following SQL String into the SQL window, and save the Query as Order_DetailsQ.

    SELECT TOP 100 [Order Details].ProductID, [Order Details].UnitPrice
    FROM [Order Details]
    WHERE ((([Order Details].OrderID) Between 10248 And 10300))
    ORDER BY [Order Details].UnitPrice DESC;
  4. Open the Query in Design View and check the order of field placement and the Sort Field.

  5. Right-click an empty area above the column grid to display the Query Shortcut Menu, select the Properties… option to display the Property Sheet. Check the image below:

  6. Ensure that the Top Values Property is set to 100 to filter the Query to 100 records with the highest Unit Price values.

  7. Change the Query View into Datasheet View to display the output records.  See the image given below:

    The Order Details table contains multiple records of the same product under different OrderIDs. In this example, we have intentionally excluded the OrderID field from the data columns, using it only in the criteria to select records with OrderIDs between 10248 and 102300, which also results in some duplicate records. As shown in the image above, several duplicate product records appear in the output. This scenario provides an opportunity to experiment with the Unique Values property settings to remove duplicates.

    Eliminating Duplicate Records.

  8. Change the Top Values property to All, and the Query to Datasheet View. The output will be about 150 records for OrderID Range between 10248 and 102300.

  9. Change the Query in Design View and display its Property Sheet.

  10. Set the Top Values property to 100 and the Unique Values property to Yes.

  11. Change the Query in the Datasheet View and inspect the output.

    Now the duplicate records are suppressed (29 records removed), leaving only 71 records in the output. The next property, Unique Records, can be set to Yes to achieve the same result when fields from two or more tables or queries are joined in a query design. This is useful when the output contains duplicate records due to a one-to-many relationship between the tables.

    We have specified 100 records in the Top Values Property, but the Unique Values property setting reduced the number of records to 71 after suppressing duplicates. 

  12. Change the Top Values Property setting from 100 to 25% and change the View to Datasheet.

Using the Percentage setting, the output returns only one-fourth of the total records. With Unique Values set to Yes, this yields 18 records, out of a total of 71. With Unique Values set to No, it returns 39 records, which is approximately one-fourth of the total 150 records.

The Top Values Property sets can be a specific number or a percentage of Total Records.

Share:

Attachment Field in Access2007

Attachment Field in Access 2007.

Working with images or animations in applications like Microsoft Access has always been enjoyable. I have used the Office Assistant for message boxes in all my Access applications, particularly when creating and deploying common VBA library programs across the network.

Not everyone may know that it is possible to display custom images in the Office Assistant control. I have leveraged this feature to display custom greetings to Access users on special occasions such as Christmas, Eid, and Onam simply by replacing the standard company logo image on the server. I was extremely disappointed when Microsoft removed this feature in Office 2007.

For those still using Microsoft Access 2003 or earlier, the following links provide tips and tricks for using the Office Assistant with MsgBox:

The Attachment field type in Access 2007 has significant flexibility, allowing multiple external documents or images to be stored in a single record without inflating the database size. This overcomes the limitations of the older Object Linking and Embedding (OLE) method, which was commonly used in earlier MS Access Versions for storing, editing, or displaying images. While a Hyperlink field can link to only one external file or a single internal object (such as a form or report), the Attachment field supports multiple items per record.

This feature is useful for storing and retrieving essential documents related to a record, such as project site plans, diagrams, contract agreements, engineering drawings, or employees’ family photos. Each attached document or image can be edited in its native application, preserving full functionality.

A Sample Demo.

  1. Open Microsoft Access 2007.

  2. If you have already created the Northwind 2007 sample database, open it; otherwise, select Local Templates from the Template Categories.

  3. Click on the Northwind 2007 Template to select it.

  4. Click the Folder icon on the right side of the File Name control, select the required folder, and save Northwind 2007.accdb Database.

  5. Open Northwind 2007.accdb Database,

  6. Close the Home Form.

  7. Select Object Type from the drop-down list in the Navigation Pane and select Tables.

  8. Right-click on the Employees table and select Design View from the Shortcut Menu.

  9. Use the right scroll bar to move the field list up and bring the last field, Attachments (field type: Attachment), into view.

  10. Now that we have seen the Attachment Field in the Employees Table (or you can create a new Table with the Attachment Field if you prefer), close the Design View.

  11. Open the Employees Table in Datasheet View.

  12. Move the horizontal scroll bar and bring the attachment field into view. See the sample image shown below:

  13. The second column (highlighted) is the attachment field where a paper clip image and a number in brackets (zero) display how many attachments are in each record.

  14. There are no attachments in any of those records so far, so we will add one; double-click the attachment field in the first record.

  15. The Attachment control opens up. Click on the Add… Command Button to browse for files on the hard disk. You may select a Word Document, Excel File, PDF file, or Image.

  16. Repeat this action to attach more files to the same field.

  17. Click OK to close the dialog box.  You will now see a number appearing in brackets, indicating how many attachments are in that field of the record.

  18. Double-click the attachment field to open and show the attached files.

  19. Click on one of the files to select it.

  20. If you click on the Remove Command Button, you can remove the selected attachment, or click Open to open the document in its parent/preview Application.

  21. If you right-click the attachment field, the Manage Attachment shortcut menu is displayed.  Selecting this option will open the earlier dialog box we have seen for attaching /removing/opening external files.

Technorati Tags:
Share:

PRESENTATION: ACCESS USER GROUPS (EUROPE)

Translate

PageRank

Post Feed


Search

Popular Posts

Blog Archive

Powered by Blogger.

Labels

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