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

Sunday, January 30, 2011

Embedded Macros in Access2007

Embedded Macros in Access2007.

The only difference between stand-alone macros and embedded macros is that embedded macros do not appear in the Navigation Pane under the Macros group. Instead, they are written directly within a Form, Report, or a control’s event property. When you copy a Form or Report, its embedded macros go with it.

Let’s now explore how embedded macros are created.

Creating Embedded Macros.

  1. Open Microsoft Access 2007.

  2. Open a Report in Design View.

  3. Press F4 or Alt+Enter to display the Property Sheet of the Report.

  4. Click on the Event Tab of the Property Sheet.

  5. Click on the On Load Event Property to select it.

  6. Click on the Build (...) button on the right side of the property.

  7. The Macro Builder option is already in selected state. Click the OK Command Button to accept it.

    The Macro is open in Design View.  The title bar of the macro indicates Catalog:Report: On Load (the Report Name: Object Type: Event Type), where the macro will be embedded. 

  8. Select MsgBox Action and type my Embedded Macro in the Message Action Argument.

  9. Type the On Load Info in the Title Argument of MsgBox Action.

  10. Click on the Close Toolbar button to save and close the Macro.

  11. Save and Close the Report.

  12. Right-click the Report in the navigation pane and select Open to open the Report in Report View.  The embedded macro will run, and you will see the message.

  13. You can modify the macro by following steps 2 to 6.  You can add several actions in the Macro if needed.

Friday, January 21, 2011

Report Design in Access2007

Report Design in Access2007.

In Microsoft Access 2007, two new design-time features are available: Report View (different from Print Preview) and Layout View, in addition to the traditional Design View and Print Preview. These new views make working with reports more interactive.  In earlier versions of Access, only Design View and Print Preview were available.

Report View looks similar to Print Preview but offers additional functionality. You can search within the report, copy data to the clipboard, filter records, and even view summarized values of the filtered data. If you’d like to preserve the filtered records so that they appear each time the report is opened, simply set the Filter On Load property to Yes.

Layout View is somewhat similar to Design View, but with one important difference—you can make design adjustments while viewing the actual report contents. In this view, you can rearrange fields, add or remove fields, adjust field sizes, and modify data field properties, with the changes immediately reflected in the report output.


The Report View Feature.

  1. Let us try out the above features; Open Microsoft Access 2007.

  2. Open one of your Databases.

  3. Import the Order Details Table from the Northwind.mdb sample database.

  4. Click on the Table to select it.

  5. Click the Report Option from the Create Menu to create a Report with the basic design and save it named Order Details.

  6. Right-click the Order Details Report in the navigation pane, select Open to open the report in Report View.

Now, let us try search, filter, and copy operations in the Report View mode.

  1. Click on the OrderID field in the first record on the Report to select it.

  2. Click on the Find Toolbar button (the field-glass icon) under the Home menu.

  3. Type 10251 in the Find What control and click the Find Next Command Button.  The first record with OrderID number 10251 is highlighted.  You can repeat the search operation by clicking on the Find Next Command Button.

  4. Let us incorporate the filter action; click the Cancel Button to cancel the Find operation and close the dialog box.

  5. Click on the Filter Toolbar Button.  The following filter control will be displayed over the report.

  6. Click the Select All option to remove all the check marks.

  7. Put check marks on OrderID Numbers 10251 and 10255.

  8. Click the OK Command Button to filter records with the selected OrderIDs on the Report.

  9. You can click the Toggle Filter Toolbar button to display all the records or filter the records again.

To copy selected records from the Report to the Clipboard:

  1. Click and hold the left mouse button at the left border of the topmost record in the report, and drag over a few records to highlight and select them.

  2. Click the Copy toolbar button in the Home Menu to copy the highlighted records onto the Clipboard.  These copied Report records can be pasted into Excel, Word, etc.

If you want to see the same set of filtered records every time you open the Report, then you must change the Report Property Value.

  1. Select the Design View option from the View Menu.

  2. Select the Property Sheet option to display the Report Property Sheet.

  3. Click on the Data Tab of the Property Sheet.

  4. Set the Filter on the Load property value to Yes.

  5. You can add or remove OrderID numbers in the IN clause of the Filter condition in the Filter property value if needed.

  6. Save the changes and close the Report.

  7. Open the Report in Print Preview and check whether the filter action is in effect.

  8. Close the Report.

The Layout View Feature.

Now, it is time to try out the Layout View options.

  1. Right-click on the Order Details Report in the navigation pane.

  2. Select Layout View from the displayed shortcut menu.

  3. Click and hold on the OrderID heading, and drag and drop it after the Discount Column.  You can do this with the column header, and also on any row of records.

  4. Click any row in the Discount column to select the column.

  5. Press the Delete key to remove the column from the Report.

    Let us try to bring that column back into the Report from the Source Table Field List.

  6. Click on the Add Existing Fields Toolbar Button from the Format Menu.

  7. Drag the Discount Field and drop it between the Unit Price and OrderID fields.

  8. While the Discount Field is still in selected state, click on the Arrange Menu to display its Toolbar.

  9. Click on the Property Sheet Tool to display the Property Sheet of the Discount Field.

  10. Click on the Format Tab of the Property Sheet.

  11. Change the Decimal Places property value to 2 and change the Width Property value from 1 inch to 0.75 inches.

The interactivity feature is very powerful in the designing process of Microsoft Access Reports and makes the design task easier and more interesting, too.

Technorati Tags:

Thursday, January 13, 2011

Memo Field Text Formatting

Memo Field Text Formatting.

We know that Memo fields in Microsoft Access tables provide the flexibility to store variable-length text data. However, in Access versions before 2007, these fields only supported plain text—much like working in Notepad.

For a long time, users felt the need for richer formatting options, such as creating numbered or bulleted lists, or highlighting key points to emphasize important information.

With the release of Microsoft Access 2007, this long-awaited feature finally arrived.

A Sample Quick Run.

Let us quickly find out how it works.

  1. Open Microsoft Access 2007

  2. If you have an earlier version of the Northwind.mdb sample database, open it. Otherwise, select Sample from the displayed list of templates and choose the Northwind 2007 template.

  3. Open the Employees Table in Design View.

  4. Click on the Notes Field to select it.

  5. Click on the Text Format Property on the General Tab of the Field Properties Sheet.  The current value of the Property is Plain Text.

  6. Select Rich Text from the drop-down list to replace Plain Text.

  7. You will see a warning message below; click Yes to apply the change.

  8. Close the Design View and save the changes.

  9. Open the Employees Table in Datasheet View.

  10. Expand the Row Height of the records by dragging the intersection of the two records at the left border.

  11. Bring the Notes Field values into view by moving the Scrollbar to the right and increasing the column width; see the image below.

  12. You can now format the Memo Field Text as you would apply formatting in MS Word.

  13. In the example image above, I have created a Numbered List, Bullet Text, applied Bold, Italics, highlighting, and alternate rows fill/backcolor.

Sunday, January 2, 2011

Sub-Query in Query Column Expressions

Sub-Query in Query Column Expressions.

Queries are the primary data processing tools in database systems. They work behind the scenes, shaping raw data into meaningful outputs such as reports and summaries. Many Microsoft Access users, especially beginners, try to build a report’s output data by chaining multiple tables/queries together in a single query, expecting the final result in just one or two steps. This approach often leads to difficulties in producing the correct output.

A better method is to start by planning the report—define its layout, required contents, grouping, and summarizing needs. If multiple related tables are involved, break down the process into smaller, manageable steps. Begin by joining a few tables or queries to create a new query, then use that query as input for the next step. You can also create intermediate tables and build further queries on top of them to refine the data. In this process, make use of action queries such as Make-Table, Append, or Update to prepare and organize the data effectively.

When the Report Requirement is Complicated.

When a report’s contents are complex and cannot be built in a single step, my preferred approach is to create a Report Table. Data is brought into this table piece by piece from the source tables using queries or VBA routines, and then added or updated as needed before opening the report. Once the Report Table is populated, the report design becomes straightforward, since it is bound to a single, well-structured dataset.

These preparation steps can be fully automated with Macros or VBA.

To make the process flexible, necessary report parameters—such as date ranges or filter criteria—are stored in a Parameter Table. A Parameter Form is provided to capture or update these values. From this form, users can either:

  • Re-run the procedure to refresh the Report Table with new parameter values, or

  • directly open the report in Preview/Print mode if the data has already been prepared.

Using a Sub-Query in the Criteria Row.

Here, we will explore how to use Subqueries within Queries to filter records or incorporate data from other tables or queries.

Let us look at a simple Query that uses a sub-query in the criteria section to filter data from the Orders Table.   In the Orders table, there are about 830 Orders, and the OrderIDs range from 10248 to 11077.  We need to filter certain Groups of Orders (say Order Numbers 10248, 10254, 10260, 10263, 10267, 10272, 10283) for review.

The following is the sample SQL query that filters the above Orders without the use of a Sub-Query:

SELECT Orders.*
FROM Orders
WHERE (((Orders.OrderID) In (10248,10254,10260,10263,10267,10272,10283)));

The above query works, but it has a limitation that whenever we want to filter a different set of Orders, we must manually modify the Criteria line by replacing the existing Order Numbers with the new ones. Clearly, we cannot expect end users to perform this task themselves.

A better approach is to provide users with a simple option to enter the required Order Numbers into a dedicated table (let’s call it ParamTable, with a single field: OrderNumber). This way, the query can automatically detect any changes to the table values at runtime. Users can type the desired Order Numbers directly into a Datasheet Form, and then click a Command Button to run the query with the updated values.

To achieve this, we need to use a subquery in the criteria row of the main query. The subquery compares the OrderNumber values in the ParamTable with those in the Orders table, ensuring that only matching records are returned.

We will modify the Query in the Criteria Row to insert a subquery to get the values from the ParamTable and use the OrderNumber field values as Criteria. 

The modified SQL String of the Query is given below:

SELECT Orders.*
FROM Orders
WHERE (((Orders.OrderID) In (SELECT OrderNumber FROM OrderParam)));

The Sub-Query string in the Criteria Row is in Bold in the SQL above.

The Sub_Query in a Query Column.

You may have already encountered the type of subquery shown above, but now we will explore a different approach: employing a subquery as an expression in a query column. This allows us to bring in values from another table related to the Query source table. Although this technique is not commonly used, it can be extremely valuable in complex scenarios where conventional joins or query structures fall short.

When several tables are used in a Query with LEFT JOIN or RIGHT JOIN relationships, it becomes difficult to link all the related tables this way to incorporate summary values of one table. This is more so when one-to-many relationships are involved.

We will use the Orders and Order Details Tables from the Northwind.mdb sample database for our example. Import both these tables from the Northwind.mdb sample database from C:\Program Files\Microsoft Office\Office11\Samples\Northwind.mdb.

The sample Query (in normal style) uses both Tables in the Query, linked to the OrderID Field of both tables to create an Order-wise Summary from the Order Details Table.

SELECT Orders.OrderID,
 Orders.CustomerID,
 Sum((1-[Discount])*[UnitPrice]*[Quantity]) AS OrderVal
FROM Orders INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID
GROUP BY Orders.OrderID, Orders.CustomerID;

The same result can be achieved without placing the Order Details Table in the Query design. We will write an expression in a separate Column using a subquery to pull the Summary Order-wise Total Value directly from the Order Details Table. Here is the example SQL String:

SELECT Orders.*,
    (SELECT  Sum((1-[Discount])*[UnitPrice]*[Quantity]) AS OrderValue
     FROM [Order Details] AS ODetails WHERE ([ODetails].[OrderID] = [Orders].[OrderID])
GROUP BY [ODetails].OrderID) AS OrderVal, [OrderVal]*0.12 AS Tax
FROM Orders;

In the Orders table, each order can have multiple related records in the Order Details table. By using a subquery (a totals query), we can calculate the total sales value for each order. The result of this calculation is then displayed in the corresponding row of the output. In other words, the subquery functions as an independent expression in its own column, running separately for each row in the Orders table.

The new column name OrderValue, created, can be part of other expressions, and we have calculated the Tax value, 12% of Order Value, in a separate column.

Let us take a closer look at the Sub-Query.

  1. The SELECT clause uses only one output column (Sum((1-[Discount])*[UnitPrice]*[Quantity]) AS OrderValue), and the expression is named OrderValue.  You should not use more than one column in the SELECT clause.

  2. In the FROM clause, the Order Details Table is given a new name (ODetails), and the name is used to qualify the OrderID field in the WHERE clause.  The OrderID field appears in both the Orders and Order Details Tables.

  3. The WHERE clause in the Subquery is necessary to match the OrderIDs of the tables and place the calculated value of the Order row matched Records.

Earlier Post Link References:

Powered by Blogger.