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

Designing About Form for MS-Access Project

Designing the About Form for an MS Access Project.

This is all about the Microsoft Access About Form.

Once your Microsoft Access application development process is complete, you may design a small form called the About Form for your project. The About Form typically displays your project’s logo, name, version number, copyright information, and any other details you wish to include.

A sample About Form image of the Windows Live Writer Application is given below as an example:

Designing an Access About Form is straightforward. You will typically need:

  • Two Label controls to display the application name and the current version number.

  • A Textbox to show the copyright information.

  • An Image control (optional) to include your custom logo, giving your application a unique identity.

Designing a Simple Access About Form.

Let us design such a small About Form to know what it takes to create one with a simple Logo. Our sample About Form in design view is given below for reference.

I have designed a simple logo in MS Word, captured a screenshot of it, modified it in MS Paint, and saved it as a .bmp file.

  1. Open your Microsoft Access Application.

  2. Create a new Blank Form.

  3. Set the Width Property value of the Form to 3.93"

  4. Click on the Detail Section of the Form to select it.

  5. Set the Height property value to 1.53".

  6. Insert an Access Image control from the Toolbox on the left side of the Form and select the Project Logo image from your computer. You may select the Picture Property of the Image control and click the Build (...) button to browse and select the logo image from your computer, if you wish to change the image later.

    The Image Properties.

  7. Change the Image property values as given below:

    • Picture Tiling: No

    • Size Mode: Zoom

    • Picture Alignment: Center

    • Picture type: Embedded

  8. MS Access Label & Text Controls.

  9. Insert a Label control to the Logo's right and the Form's top position, and resize it wide enough to write the Application name in bold letters.

  10. Write the Project Name in the Caption Property, and set the Text Font size to your liking, make it bold, and align the text to the center.

  11. Create another Label control below the first one, with the same width as the first label. Write the Version number of your Project, make it bold, and centralize the text.

  12. Insert a Textbox below the earlier labels, and with the same width.

  13. Copy and paste the following expression into the Control Source property of the textbox. ="Copyright " & Chr$(169) & Year(Date()) & " All Rights Reserved".

  14. Change the TextBox Property values as given below:

    • Border Style: Transparent

    • Text Align: Center

    • Enabled: No

    • Locked: Yes

    • Tab Stop: No


    MS-Access Command Button.

  15. Create a Command Button below the TextBox and position it centralized.

  16. Make the following changes to the Command Button:

    • Change the Name property value to cmdOK.

    • Change the Caption property value to OK.

    • Click on the Event Tab of the property sheet.

    • Select the On Click property and select [Event Procedure] from the drop-down list.

    • Click on the Build (...) button to open the VBA Module with the empty procedure start and end lines.

    • Copy the middle line of code given below and paste it in the middle of the Subroutine Stub. Or copy all three lines and paste them, overwriting the existing lines in the VBA Module.

    • Private Sub cmdOK_Click()
      DoCmd.Close
      End Sub
      

      The Command Button Click closes the About Form.

  17. Save the Form and rename it as About or frmAbout.

  18. Open the About Form in Normal View and see how it looks on the Access Application Window.

    The Property Value Changes.

    As you can see, the Access About Form needs some changes to make its appearance like a real About Form. Let us do that to give it the final touches.

  19. Make the following changes in the Form's Property Values as shown below:

    • Caption: About <your Project name here>

    • Pop Up: Yes

    • Modal: Yes

    • Default View: Form View

    • Allow Form View: Yes

    • Auto Center: Yes

    • Auto Resize: Yes

    • Fit to Screen: No

    • Border Style: Dialog

    • Record Selectors: No

    • Navigation Buttons: No

    • Dividing Lines: No

    • Scroll Bars: Neither

    • Control Box: Yes

    • Close Button: No

    • Min Max Button: None

  20. Save the Form after the above changes.

    View The Application About Form in Normal View.

  21. Open the About form in Normal View.

    A sample Image of the completed About Form in Normal View is given below.

You must add an Option to the Customized Menu of your Project to enable the User to open the Access Application About Form. Alternatively, you may add a Command Button on the Main Form of your Project to do that.

Share:

Appending Data from Excel to Access

Appending Data from Excel to Access.

Last week, we tried out an interesting method of writing a range of Excel data directly into a Microsoft Access Table. Each row of data is transferred to the table as a single record. If you haven't come across that article, then you may find it here.

This is an equally interesting method.  The selected Worksheet contents are appended to the Access Table with its specified columns in the SQL.

A sample image of the Worksheet data is given below:


The VBA Code

Private Sub CommandButton1_Click()
On Error GoTo CommandButton1_Click_Error
'Create Database connection Object
Set cn = CreateObject("ADODB.Connection")
'Access Database must be in the same location of the Worksheet 
dbpath = Application.ActiveWorkbook.Path & "\Database4XL.accdb"
'Get Workbook Full Pathname
dbWb = Application.ActiveWorkbook.FullName
'Get Active worksheet name
dbWs = Application.ActiveSheet.Name
'Create Data Target Connection string to open a session for data transfer
scn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbpath
'Datasheet name to add at the end of the Workbook Name, to complete the
'FROM clause of the SQL String.
dsh = "[" & dbWs & "$]"
'Open session
cn.Open scn

'Append Query SQL String
ssql = "INSERT INTO Table1 ([Desc], [Qrtr1], [Qrtr2], [Qrtr3], [Qrtr4]) "
ssql = ssql & "SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

'Run SQL
cn.Execute ssql

MsgBox "Data Added to " & dbpath & " Successfully."

CommandButton1_Click_Exit:
Exit Sub

CommandButton1_Click_Error:
MsgBox Err & " : " & Err.Description, , "CommandButton1_Click()"
Resume CommandButton1_Click_Exit

End Sub

Courtesy:
The above VBA code was taken from a Forum Post on www.mrexcel.com/Forum and modified to run on the same sample data presented in the earlier article published last week.

The CommandButton1 Click Event Procedure is run from the Excel Worksheet VBA Module.

  1. Roundup Function of Excel in MS-Access
  2. Proper Function of Excel 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 an Excel Word File from Access
Share:

Writing Excel Data directly into Access Table

Writing Excel Data directly into an Access Table.

Microsoft Access allows you to import data from external sources such as dBase, FoxPro, Excel, or even another Access database. Likewise, you can also export data from Access to these applications, making data exchange and integration seamless.

Following is a list of topics I have published earlier, either on importing, exporting, or working with external data sources from Microsoft Access:

Today, we will explore how to add a range of Excel cell data directly into an Access Table by running the VBA Code from within Excel.

The Algorithm of the program is as given below:

  1. Create an Access Application Object and open it.

  2. Open the target database within the Access Application.

  3. Keep the Access Application window hidden.

  4. Open the target table from the Database.

  5. Count the rows in one of the Excel data columns.

  6. Open a loop to write the Excel data one row at a time, starting from the second row onward.

  7. Repeat the writing action till all the rows are transferred to the Access Table.

  8. Close the table and the database and quit the MS Access Application.

The Excel VBA Code is run by clicking a Command Button on the Excel Sheet. A sample image of the Excel Sheet with data and a Command Button is given below:

The Target Table Structure image is given below:


The Excel VBA Code

Sub Button1_Click()
    Dim objAcc As Object
    Dim recSet As Object
    Dim DataRow As Long, EndRow As Long
    
    On Error GoTo Button1_Click_Err
    
    'Create Access Application Object
    Set objAcc = CreateObject("Access.Application")
    'Open Database in Microsoft Access window
    objAcc.OpenCurrentDatabase "F:\mdbs\Database4XL.accdb", True
    'Keep Access application window hidden
    objAcc.Visible = False
    
    'Open Access Table to add records from Excel
    Set recSet = objAcc.CurrentDb.OpenRecordset("Table1")
    'Take actual row counts of data for transfer
    EndRow = Sheet1.Range("A" & Rows.Count).End(xlUp).Row

    With recSet
      For DataRow = 2 To EndRow
        .AddNew
        ![Desc] = Sheet1.Range("A" & DataRow).Value
        ![Qrtr1] = Sheet1.Cells.Range("B" & DataRow).Value
        ![Qrtr2] = Sheet1.Cells.Range("C" & DataRow).Value
        ![Qrtr3] = Sheet1.Cells.Range("D" & DataRow).Value
        ![Qrtr4] = Sheet1.Cells.Range("E" & DataRow).Value
        .Update
      Next
    End With
    recSet.Close
    objAcc.Quit
    Set objAcc = Nothing

Button1_Click_Exit:
Exit Sub

Button1_Click_Err:
MsgBox Err & " : " & Err.Description, , "Button1_Click()"
Resume Button1_Click_Exit
    
End Sub
Courtesy:
The non-functional raw VBA Code presented by a User at the Excel Forums www.mrexcel.com/forum/microsoft-access was modified by me to make it functional and was originally submitted there.

The first field of the table is an ID field with the data type AutoNumber. The ID field value is automatically generated when data is inserted into the other fields.

  1. Roundup Function of Excel in MS-Access
  2. Proper Function of Excel 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 an Excel Word File from Access

Share:

Legacy Custom Menus Toolbars in Access2007

Legacy Custom Menus Toolbars in Access2007.

Custom Menu of Access 2003 in Access 2007.

You may have invested considerable time designing custom menus and toolbars in your MDB database. However, after upgrading to Microsoft Access 2007 and opening your database with the new version, you might notice that the customized menus and toolbars have disappeared.

The Add-In Menu.

Your custom menus and toolbars are not lost—they are still available. In Microsoft Access 2007, they are stored under the Add-Ins tab. Simply click the Add-Ins tab on the Ribbon to find all your custom menus and toolbars there. Refer to the sample image below for guidance.

Have you noticed the group name Custom Toolbars appearing at the bottom of the Add-in Menu?

But the Access 2007 Menu Bars also appear at the top.  You want to turn off the default Access 2007 Menus and Toolbars from the top and replace them with your Custom Menus and Toolbars.


Access Option Changes.

Do the following to get that done:

  1. Click the Office Button (Top-left corner).
  2. Select Access Options.
  3. Select the Current Database.
  4. Move the scroll bar down to find the Ribbon and Toolbar Options as shown in the image given above.
  5. Select your Custom Menu Bar name from the drop-down list, replacing the text (Default).
  6. Select your Shortcut Menu Bar name from the drop-down list, replacing the text (Default).
  7. Remove the check marks from the next three options:
    • Allow Full Menus.
    • Allow Default Shortcut Menu.
    • Allow Built-in Toolbars.
  8. Click OK to save changes to Access Options.

  9. One more step to go:

  10. Close the database and reopen it to register the changes.

Now that the Menu Bars and Tool Bars are in complete control of your Application, they will look like the image given above.

To restore Access 2007 Menus and Toolbars, open the MDB file by holding the Shift key to prevent Auto-Macro from running and to get control of the database window.  Go through Steps 1 to 9 and reverse what you did earlier.

Share:

Sub-Report Summary Value in Main Report Calculations

Sub-Report Summary Value in Main Report Calculations.

How to bring the sub-report summary value to the main report and use it in calculations?

But first, we need a ready-made report for our project.

Download links for the sample database are provided below. Choose the version you need. The demo database is created in Microsoft Access 2007 format and is fully compatible with later versions.

First, take a look at the following images:

  1. Print Preview of the finished report.
  2. Original Report Preview. 
  3. Changes were made to the Report in Design View to get the result shown in the first image above.


    Download Links.

  4. Sample Database Download Links for Microsoft Access 2007 and 2003 Versions are given below.


  5. Download the suitable sample database.

    In short, our task is to add the sub-report category total to the Footer Section of the Sales by Category sub-report. Get the summary value of each category for the main report header.  Calculate the percentage of each category of product sales value on Grand-Total Sales Value (or Percentage = Category Sales Value / Total Sales value of all Categories * 100).  We can do this by adding a few text boxes to both reports and writing a few expressions in them.

    The Sub-Report Changes.

    Let us start with the Sales by Category Sub-report first.

  1. Open the downloaded database.

  2. Open Sales by Category Sub-report in Design View.

  3. Right-click on the Report Footer bar and select Properties to display the Property Sheet.

  4. Select the Height Property and change the property value to 0.33” or 0.838 cm.

  5. Select the Text Tool from the Toolbar above and draw a text box on the Report Footer area below the Product Sales column.

  6. Write the expression =Sum([ProductSales]) in the Control Source property of the text box. Change the Name property value to SubTotal.

  7. Modify the Caption property value of the child label to read as Sub-Total.

  8. Save and close the Sales by Category Subreport.

    The Main Report Changes.

  9. Open the Sales by Category main report in Design View.

  10. Create a TextBox on the Header Section of the Report, to the right of the report heading.

  11. While the text box is in selected state, display the property sheet (F4).

  12. Write the expression =Sum([ProductSales]) in the Control Source property. Change the Name property value to TotalSales. Change the Caption property of the child label to Total Sales.

    Note: The expression calculates the total product sales value across all categories on the main report. When used in the sub-report, however, the same expression calculates the sales value of the current product category (for example: Beverages). This gives us two values: the SubTotal for a specific category in the sub-report, and the TotalSales for all categories in the main report.

    With these values, we can calculate the percentage contribution of a particular category using the formula:

    Percentage=SubTotalTotalSales×100\text{Percentage} = \frac{\text{SubTotal}}{\text{TotalSales}} \times 100

    However, since SubTotal is calculated in the sub-report, it cannot be referenced in the parent (main) report. To use it in the main report—especially when there are multiple sub-reports—we must explicitly specify the location of the control or expression within the sub-report.

  13. Create a text box below the Category Header bar to the right of the Category Name heading, and relocate the TextBox under the Total Sales calculation control on the Report Header.

  14. Right-click on the Control Source Property of the text box and select the Build option from the displayed list to open the expression builder control.

    • Click on the = symbol to insert it into the expression editor window.

    • Double-click on the + symbol on the left side of the Reports option to expand and show other options.

    • Double-click on Loaded Reports.

    • Double-click on the Sales by Category main report to display the Sub-Report's name.

    • Click on Sales by Category Subreport to display its control names in the next column.

    • Find the Subtotal control in the list and double-click on it.

      The reference to the SubTotal control in the subreport can be written as:

      [Sales by Category Subreport].[Report]![SubTotal]

      This reference can be inserted directly using the Expression Builder. Alternatively, if you already understand how to write the reference correctly, you can type it directly into the Control Source property without going through the Expression Builder.

      With practice and by studying Microsoft Access’s addressing conventions, you will quickly become comfortable writing these references manually for use in Reports or Forms.

    • Click Ok to return to the TextBox Control Source property, with the Subtotal Reference, and write the rest of the expression to calculate the percentage.

    • Type /[TotalSales] at the end of the subtotal reference. Have you noticed the slash on the left side of the expression snippet?

    • Select Percent from the Format Property drop-down list. With these settings, we don’t have to write the *100 part in the expression.

    • Change the Caption of the child label to Category %. Change the TextBox and Child label Font Size to 12 points and Font weight Bold.

    Report Sample Print Preview

    Our Report is almost finished, but we need a little more change, and that comes next after we preview the progress of our work so far

  15. Save the changes we have made to the Report, and open it in Print Preview to see how the changes appear on the Report.

    The Report should look like the image below.

  16. Move the Report to the next page.

    The Total Sales value of the Report Header Section is not appearing on the second page.

    By default, the Report Header section prints only on the first page of the report, and the Report Footer section prints only on the last page. This means that any headings or calculations placed in the Report Header will not appear on subsequent pages.

    However, we often want the report heading and certain calculated values to appear on every page. Content placed in the Page Header section is repeated across all pages, making it the ideal place for such information.

    The challenge is that aggregate functions Sum(), Count (), and similar expressions do not work in the Page Header section. For example, we cannot place a SUM() calculation there. But we do want the calculated result from the Total Sales control (defined in the Report Footer or another valid section) to appear consistently at the top of every page.

    To achieve this, we make the following adjustments:

    Move the report heading from the Report Header to the Page Header, so it prints on every page.

    Reference the Total Sales control (which performs the calculation in a valid section, such as the Report Footer) from within the Page Header. By pointing to the existing Total Sales control, its value can be displayed in the Page Header even though aggregate functions cannot be calculated there directly.

    With this approach, both the heading and the calculated Total Sales value will appear consistently on every page of the report.

    The Final Changes.

    • Open the report in design view.

    • Drag the Category Name header bar down to get enough space for the Page Header Section, then cut and paste the Report Heading there.

    • Highlight the report heading and the report date controls (leave the Total Sales textbox alone), cut, and paste into the Page Header Section.

    • Select the Total Sales text box, copy and paste it into the Page Header Section, and move the position below the text control on the Report Header Section.

    • Write the expression = [TotalSales] (the Name of the Total Sales calculation text box on the header section) in the Control Source property (overwriting the existing expression) of the copied text box.

      This will display the value of the Header Section text box, where the Total Sales value is calculated.  

    • Select the Header Section text control and the child label and set their Visible property to No to keep it hidden when the report is previewed or printed.

    • Save the report with the changes.

      Print Preview the Report.

    • Open the Sales by Category report in Print Preview, move the pages forward, and check the headings and category percentage values.

  17. Next time you want to do something like this, you can do it in a few minutes.

Share:

Editing Hyperlink Address Manually

Editing Hyperlink Address Manually.

Hyperlinks are everywhere on the Internet, and Microsoft Access supports them, too. In Access, hyperlinks can be used to open objects—such as Tables, Forms, Reports, or Queries—with a simple click, without writing a single line of VBA code or creating a Macro. They can also be created in Tables or Forms to build menus that open various database objects. Beyond Access, hyperlinks can launch external files such as Word documents, Excel worksheets, PDFs, and text files.

In Access, hyperlinks can be created or edited manually by entering their different segments in the correct order, either in a table field or on form controls. More commonly, editing is done through the Edit Hyperlink dialog box, which appears when you right-click on a hyperlink control. 4 Segments of Hyperlink-Address in MS Access.

The Hyperlink address line is divided into four segments:

  1. Display Text: the text that appears in a field or control, indicating the hidden link's purpose
  2. Address: external file's path-name
  3. Sub-Address: Internal Object Name, to open Form, Report, etc.
  4. Screen-tip: the text displays as a tooltip.

Hyperlink syntax is as follows:

Display Text#Address#Sub-Address#Tool-tip text

The Hyperlink Data type field size is 2048 characters.

You can find more details and usage of Hyperlinks in the earlier Post: Open Forms with Hyperlinks in Listbox.

Editing Hyperlink Manually.

Let us get into the manual editing of the Hyperlink topic:

We will create a sample table with a Hyperlink field to try out the manual editing exercise.

  1. Create a table with a single field and data type Hyperlink.
  2. Save the table with a name.
  3. Open the table in datasheet view.

    If you know how to enter Hyperlink data into the field manually, you may do so by following the hyperlink syntax shown below.

    Example: My Excel File#C:\\\My Documents\Workbook1.xls##Click

  4. After entering the sample hyperlink in the field, open the table in the datasheet view.

    You will see that the hyperlink field is active, and the only text showing is the Display Text (My Excel File) part of the hyperlink information.

  5. Move the mouse over the hyperlink field; it changes to a hyperlink pointer (a Hand with the index finger extended).

    If you click on the field to edit the hyperlink information, it will only open the document specified in the second segment.

    If you right-click on the field, the shortcut menu, which carries the hyperlink editing options in a dialog box, is displayed.  You may key in values at appropriate segments to change the hyperlink values.  You cannot type values directly into the hyperlink field.

    Simple Trick to Edit Hyperlink Manually.

    But we can manually edit the field with a simple trick.

  6. Close the Table for now.
    • Click the Office Button.
    • Select Access Options.
    • Select Advanced.
    • Find the Behavior Entering Field options.
    • Select the Go to end of the field Option.
    • Click OK to close the Access Options control.
  7. Open the Table after completing the above steps.

You can see that the insertion point is positioned at the end of the field value, exposing the hyperlink information. Move the insertion point back to the location where you need to edit the field.

If you have more than one record to edit, then change them and reset the Behavior Entering Field option to Select Entire Field.

TIP:

If you would like to show the full File Pathname as display text, copy the Second segment hyperlink value and paste it into the display text position too.


Stand-alone Label Controls Have Hyperlink Properties.

The Label control on the Form can be used as a hyperlink control.  The label control has Hyperlink Address & Hyperlink Sub-Address properties; use the Caption property to set the Hyperlink Display Text. Set the Special Effect property value to Raised to make it look like a Command Button.

Share:

Alphabetized Customer List

Alphabetized Customer List.

If you are new to Microsoft Access report design, this simple tutorial on creating an alphabetized customer list will give you a clear understanding of the basics. It provides valuable insight into the steps involved in designing a report. We will need the following steps to complete our task:

  1. Prepare the Customers' source data in a SELECT Query for the report.

  2. Open a new report in Design View.

  3. Insert the SELECT Query name into the Record Source Property of the Report.

  4. Use the Data Grouping and Sorting option of the Report to organize and display A, B, C, etc., in the Group Header.

  5. Design the Report.

  6. Preview the Report.

A Sample Report.

Sample alphabetized list of customers. Report Preview is given below:


Designing A Report.

Get Some Sample Data.

But first, we need some ready-made sample data for our Report

Let us start by importing the Customers Table from the Northwind sample database.

  1. Click on the External Data Menu.

  2. Click the Access Tool button to display the Import control dialog box to specify the Source and destination of data.

  3. Click on the Browse... button to locate the Northwind sample database, select the file, and click Open.

    The selected file pathname is inserted into the File Name control in the dialog box.

    The first option is already selected as the default to import one or more required Access Objects from the selected Access database.

  4. Click OK to open the selected Access Database and expose its Tables, Queries, Reports, etc.

  5. Click the Tables tab, select the Customers table, and click Ok to import the selected table.

    The next step is to create a SELECT Query using the Customers table as the Source.

  6. Click on the Create menu and select Query Design from the Other group.

  7. Click the Close button to close the Show Table Dialog Box without selecting any object from the displayed list.

  8. You will find the SQL View option on the left of the Toolbar; select it to display the Query's SQL editing window.

    You will find the SQL statement SELECT in the window.

  9. Copy the SELECT Query Code given below and paste it into the SQL window, overwriting the existing SELECT statement.

    SELECT Left([First Name],1) AS Alpha, [First Name] & " " & [Last Name] AS CName
    FROM Customers
    ORDER BY Left([First Name],1), [First Name] & " " & [Last Name];
    

    In the SQL string shown above, we are working with only two columns of data. The first column, named Alpha, contains a single character from each row—the leftmost character of the customer’s first name—extracted using Microsoft Access’s built-in String function Left(). Access also provides other useful string functions in this category, such as Right(), Mid(), and more.

    The second column, named CName, contains the customer’s full name, created by joining the first and last names together with a space in between. When building query expressions like this, it is always good practice to assign simple, meaningful names to the calculated columns. This makes it much easier to remember and reference them later in reports or forms. If you don’t provide explicit names, Access will automatically assign generic names such as Expr1, Expr2, and so on, which can be confusing when working with queries.

    In the ORDER BY clause of the query, both columns are sorted in ascending (A-Z) order, first the Alpha column, then the CName column.

  10. Save the Query named Customer ListQ.

  11. Open the Customer ListQ in the datasheet view and check the data.

    A sample image of what we are going to create is given below for reference:

The Design Task.

Let us design the Report.

  1. Select Report Design from the Create menu.

    An empty Report is open in Design View, with its Property Sheet. The first priority is to define the CustomerListQ Query as the Record Source of our report. If the Property Sheet is not displayed, then click on the Property Sheet toolbar button to display it.

  2. Select the Data Tab on the Property Sheet.

  3. Click the Record Source Property, and click the drop-down list at the right end of the property.

  4. Find CustomerListQ Query (use the slider, if necessary) and select it from the drop-down list to insert it into the Record Source property.

  5. Click the Group & Sort Toolbar button in the Group & Totals Group under the Design Menu, if it is not in the selected state, to display the Group and Sort controls under the Report Footer Section.

  6. Click the Add a Group control displayed in the Group, Sort, and Total shown below the empty report.

  7. Click on the Alpha column name displayed in the Query columns list.

    You can see that the Alpha Group Header is between the Page Header and Detail Sections of the empty report.

    We must sort the customer names by their first character (A, B, C order) so that all names appear under the first Alpha Character. 

    Note: All Names starting with the letter A will appear under Group A, all names starting with the letter B will list on the Report under Group B, and so on.

  8. Click Add a Sort control and select CName from the list.

    Now, let us create the Report Heading, Group headings (A, B, C, and so on), and customer names to appear under each group.

  9. Click the Label control to select it, draw a rectangle for the Heading Text "CUSTOMER LIST", select Bold and Italic formatting styles, and set the font size to 16.

  10. Select the TextBox control and draw a text box on the Alpha Header Section of the report.

  11. Click the Data Tab on the Property Sheet and select Alpha from the Control Source drop-down list. Change the font style to Bold and character size to 16.

  12. Select the child label of the text box and delete it.

  13. Create another text box in the Report Detail Section, below the Alpha Header control.

  14. Select the CName Column name from the drop-down list in the Control Source property under the Data Tab in the TextBox Property Sheet.

  15. Reduce the Detail Section height by dragging the Page-Footer section to the height of the TextBox.

  16. Save the Report as Customer List.

    Print Preview the Report.

  17. Open the Customer List report in Print Preview to view.

If the Heading, Group heading, and customer list are not properly aligned to the left in your report, as shown in the first image at the top, align all the controls to the left.

Share:

Archiving Master Data

Archiving Master Data.

Over time, the Master Table in a database can grow substantially, containing thousands—or even millions—of records. Since the maximum logical size of a Microsoft Access database is only 2 GB, the Repairing and Compacting procedure does not maintain optimal performance. As the table grows, the processing time for queries and report generation will continue to increase.

Most of the older records in the master table are not required for daily or monthly reporting and querying. However, they may still be needed for year-end processes, historical analysis, or setting business targets for the upcoming year.

Typically, older records are marked with an archived flag and retained in the master table, while active records are filtered for routine reports and queries to monitor ongoing business activities. As the table size increases, this filtering and sorting process can become slower, impacting overall database performance.

Maintaining Data of the Earlier Period.

Removing old data from the main table and storing it in a separate database will significantly improve the performance of the active database. The archived data, stored in a database such as Archive.accdb, can still be accessed whenever needed for year-end processes or historical analysis.

There is no need to permanently link the archived tables to the front-end database. Instead, you can reference the archived tables in a UNION query, combining them with the active master table only when required. This combined dataset can then serve as the source for year-end processing. (More details on creating UNION queries can be found [here].)

Before we get to that, let us first see how to safely transfer old records from the master table (tblMaster) into the archive database (Archive.accdb). For this example, we will assume that the database is configured in a Front-End/Back-End setup.

The Prelude of our Action Plan.

We need the following steps to complete the process:

  1. Create a new Access Database: Archive in location C:\mdbs or in a location of your preference.

    Note: If you are working on a shared network server, create (or use an existing) folder you have access Rights to and save the Archive.accdb there. Databases stored on the server are usually included in the administrators’ daily backup routine, ensuring that your archive remains safe and can be recovered if needed. For more details, see: [Database Daily Backup].

  2. Close archive.accdb database.

  3. Open the Back-End Database.

  4. Transfer only the Structure of tblMaster into the Archive.accdb

  5. Create a SELECT Query on tblMaster with an appropriate criterion to select the old data.

  6. Open the SELECT Query in Datasheet View, take the total record count, and note it down.

  7. Change the SELECT Query into an Append Query.

  8. Save and run the Append Query to transfer the selected data directly to the Table tblMaster in  Archive.accdb.

  9. Close the BE database and open the Archive database.

  10. Open tblMaster in the archive database and check the count of records that matches the count taken earlier. If not, investigate the cause and redo from step 5 onwards, after deleting the wrong data in the tblMaster of the Archive.

  11. Close the Archive and open the BE database.

  12. Create a Delete Query that uses tblMaster with the same criteria you have used in the Append Query.

  13. Open the Delete Query in Datasheet view, note the record count, and verify that it matches the earlier recorded count.

  14. Run the Delete Query to remove the records from the tblMaster table from the BE database.

  15. Run the Repair and Compact option to reduce the database size.

  16. Close the BE database and open the FE database.

    Linking Old Data to Front-End (FE) Database.

  17. Create a Union Query to combine data from tblMaster in BE and from tblMaster in Archive.

Let us execute the above-defined Plan.

Steps 1 to 3 are self-explanatory.

In step 4: Right-click tblMaster to display the shortcut menu.

  • Highlight the Export option and select Access Database from the displayed menu.

  • Click on the Browse button and select the archive.accdb database, and click Save and return to the Export dialog box.

  • Click OK to open up the Export Options dialog box.

  • Select the Definition Only option to transfer the tblMaster Table structure into the Archive.

Step-5: Select Query Code:

SELECT tblMaster.*
FROM tblMaster
WHERE (((tblMaster.mstDate)<Dateserial(1981,1,1)));

The above criteria will select records of period 1980 and earlier.

Step 6 is self-explanatory.

Step 7: Open the Query created in Step 5 in the Design View.

  • Click on the Append Query button on the Toolbar.

  • Select tblMaster from the Table Name drop-down control in the dialog box.

  • Select the Another Database Radio Button.

  • Click on the Browse… Command Button to find the archive.accdb database, select it, and click OK to return to the dialog box in Query Design View.

  • Click OK on the dialog box to change the Select Query to an Append Query. The Sample append query SQL is given below for reference.

    INSERT INTO tblMaster IN 'C:\mdbs\archive.accdb'
    SELECT tblMaster.*
    FROM tblMaster
    WHERE (((tblMaster.mstDate)<DateSerial(1981,1,1)));
    
  • Open the Append Query in Datasheet View and check the record count with the count you took earlier.

  • If both counts match, then save the Append Query.

Step-8: Right-click the Append Query and select Open to Run the Query to extract selected data from the tblMaster table and to append it to the archive.accdb tblMaster table.

  • Click the Yes Command Button on the warning message control to reconfirm the action.

Step-9 to Step-11: Self-explanatory.

Step-12:  Sample Delete Query SQL is given below:

DELETE tblMaster.*, tblMaster.mstDate
FROM tblMaster
WHERE (((tblMaster.mstDate)<DateSerial(1981,1,1)));

Step-13 to Step-16: Self-explanatory.

Step-17: Sample Union Query SQL is given below:

SELECT tblMaster.* 
FROM tblMaster
UNION ALL SELECT tblMaster.*
FROM tblMaster in 'C:\mdbs\archive.accdb';

Save the Union Query named tblMasterQ. Use tblMasterQ as Source Data for all year-end processes or wherever you need all the data together.  For other purposes, your database will run faster.

You can continue to transfer Data, when their usage frequency reduces to Yearly, in the Archive Database and delete them from the BE database.  No other change is required anywhere.

Technorati Tags:
Share:

Updating Combobox when Not in List is Active

Updating Combobox when Not in List is Active.

This discussion focuses on the Limit-to-List property of the Combo Box. When this property is set to Yes, users cannot enter new values directly into the combo box; they are restricted to selecting from the existing list.

If a user attempts to type a value not already in the list, Access will display a message asking to choose an item from the available options.

For lists that never change—such as months of the year or days of the week—this behavior is perfectly acceptable. However, in scenarios where the list needs to evolve, such as adding new employees, products, or client names, the default approach becomes inconvenient.

By default, new items can only be added to the source table through a separate form. Even then, the updated value will not appear in the combo box until the form is closed and reopened, which is both time-consuming and not very user-friendly.

An Easy Solution.

However, we can make this process much easier for the user with a small VBA program. Instead of forcing them to open a separate form, the user can simply type the new value directly into the combo box. With their permission, the program will add the new entry to the source table and refresh the combo box instantly.

This is possible because when a user types a value that does not exist in the list, the Limit to List property triggers the combo box’s On Not In List event. By writing an Event Procedure for this event, we can prompt the user for confirmation, insert the new record into the source table, and then requery the combo box so the new item appears immediately.

The VBA Program.

The following program adds ProductID and Product Name into the Products Table and refreshes the cboProd Combo box to make the new item appear in the list immediately:

Private Sub cboProd_NotInList(NewData As String, Response As Integer)
Dim strProd As String, strName as String
Dim rst As Recordset, db As Database
Dim msg as string

On Error Goto cboProd_NotInList_Err

'continue without displaying error message
Response = acDataErrContinue

strProd = NewData
msg = "Product ID: " & strProd & " Not found in List!" & vbCr & vbCr & "Add it in Source File...?"

If MsgBox(msg, vbDefaultButton2 + vbYesNo + vbQuestion, "cboProd_NotinList()") = vbYes Then
    'Get Product Name from User
    strName=""
    'Repeat the loop if user presses enter key without entering a value
    Do While strName=""
        strName = InputBox("Product Name: ","cboProd_NotinList()","")
    Loop
    'Add ProductID and Name to the source Table
    Set db = CurrentDb
    Set rst = db.OpenRecordset("Products", dbOpenDynaset)
    With rst

      .AddNew
      ![ProductID] = strProd
      ![PName] = strName
      .Update
      .Close
    End With
    
    'make combobox control source empty
    'in preparation to refresh the combobox
    Me!cboProd = Null
    'refresh the combobox
    Me.cboProd.Requery
    'now the combobox list have the new entry
    'place the new code in the combobox control source
    Me![cboProd] = strProd
 
    Set rst = Nothing
    Set db = Nothing
Else
   'if user refuse to add the new entry into source file
   'then display the error message and exit
   Response = acDataErrDisplay
End If

cboProd_NotInList_Exit:
Exit Sub

cboProd_NotInList_Err:
MsgBox Err & " : " & Err.Description,,"cboProd_NotInList()"
Resume cboProd_NotInList_Exit

End Sub

The above code is run from the On-Not-in-List Event Procedure of the cboProd Combo box.

Share:

Overlaying Sub-Forms in Real-Time

Overlaying Sub-Forms in Real-Time.

This section is about loading two or more forms into a single Subform Control, interchangeably. Normally, we place only one form in a Subform Control, and this is done during design time. A main Form can host one or more Subforms, typically linked through the Link Master Fields and Link Child Fields properties.

Remember this: a Subform control is essentially a Container that holds a Form object reference in its Source Object property. If you clear the form name from this property, the container remains empty on the main form. By changing the Source Object value at runtime, you can load any form you want into the same subform control. This is the key to dynamically switching between multiple forms.

Let us look at a quick example of loading three different forms into a single subform control, one after the other, replacing the previously loaded form. Check the video below for a demonstration:

You can create this Form very easily. See the sample image given below:


Sample Form Design.

  1. You can either use a copy of an existing form with enough space below the existing data fields or create a blank form in Design View. In both cases, you can drag another form from the Navigation Pane and drop it onto the Detail Section. This action automatically creates a Subform Container Control and places the dragged form inside it. If you choose to create a new blank form, leave enough space above the subform to add an Option Group Control later.

  2. Display the Property Sheet (F4) of the sub-form while the sub-form container is in the selected state, and change the Name Property value to subFrm. 

  3. Change the Name Property Value of the Child Label to HeaderLabel.

  4. Create an Option Group Control above the sub-form with the existing three form names as Labels.

  5. Change the Name Property value of the Options Group Control to Frame1.

  6. Change the Default Value property value of the Options Group Control to 0.

  7. Select the After Update Event property, select [Event Procedure] from the drop-down list, and click the Build (...) button to open the VBA Editing window.

  8. Copy and paste the following VBA Code into the Module, overwriting the Private Sub Frame1_AfterUpdate() ... End Sub lines:

    Frame1_AfterUpdate() Event Procedure.

    Private Sub Frame1_AfterUpdate()
    Dim i, sub_Form As SubForm
    
    Set sub_Form = Me.subfrm
    i = Me![Frame1]
    Select Case i
        Case 1
          sub_Form.SourceObject = "frm_Session"
          Me.headerLabel.Caption = "frm_Session:"
        Case 2
          sub_Form.SourceObject = "frm_Payments"
          Me.headerLabel.Caption = "frm_Payments:"
        Case 3
          sub_Form.SourceObject = "Stationary"
          Me.headerLabel.Caption = "Stationary:"
    End Select
    
    End Sub
  9. Modify the above Code to replace the Form Names in quotes with your own form names.

  10. Press ALT+Q to close the VBA Window.

  11. Change the Child-label Caption of the Options Group control to Form Selection.

  12. Save and close the Form.

  13. Open the Form in normal view and try out the Option Group Radio buttons to load your forms into the sub-form control, in any order you like.

When Two Sub-Forms Are Linked Together.

Assume you have a Main Form (e.g., Students) that contains two subforms: frm_Session and frm_Payments. The first subform (frm_Session) is linked to the main form through a common field, StudentID—though this is not the key point here.

The second subform (frm_Payments) is not linked directly to the main form. Instead, it is linked to the first subform (frm_Session) via the SessionID field. To ensure the second subform displays only the related records, you must configure its Link Master Fields and Link Child Fields properties. The critical detail is that the Master Field reference must come from the first subform control, not the main form. This is the main challenge in setting up this type of subform relationship.

The image of the sample form is given below:

View the Demo Video of two sub-forms in action.

The limitation with the Link Master Fields property of a subform control is that it can only be set to reference field or control names at design time. It does not accept expressions or fully qualified references, and it always expects those references to come from the main form,

The simplest solution is to create an unbound TextBox on the main form and set its Control Source to an expression such as:

=[frm_Session].[Form]![SessionID]

This allows the TextBox to display the current record key value from the first subform. You can use the TextBox name as the Link Master Field for the second subform. To keep the form uncluttered, set the TextBox’s Visible property to No.

With this setup, the second subform will correctly filter its data based on the SessionID from the first subform. If you load any form that doesn't have the SessionID field into the second sub-form control, Microsoft Access will prompt for the field value set in the Link Child Fields property.

The VBA Code.

The VBA Routines that run on the CommandButtons Stationary and Payments Click Event Procedures are given below:

Stationary Command Button Click event procedure:

Private Sub cmdStationary_Click()
Dim frm As SubForm
Set frm = Me![frm_Payments]

With frm
    'load Stationary Form into the control
    .SourceObject = "Stationary"
    .Requery
End With
  'second Sub-Form Child Label Caption Change
  Me.Label7.Caption = "Stationary"
  'Enable Payments Command Button
  Me.cmdPayments.Enabled = True
  'Shift the Focus to cmdPayments command button
  Me.cmdPayments.SetFocus
  'Disable cmdStationary command Button
  Me.cmdStationary.Enabled = False
  Me.Refresh
  
End Sub

Payments Command Button Click event procedure:

Private Sub cmdPayments_Click()
Dim frm As SubForm
Set frm = Me![frm_Payments]
With frm
    .SourceObject = "frm_payments"
    .Requery
End With
'Change Header Label Caption
Me.Label7.Caption = "frm_payments"
'Enable Stationary Command Button
Me.cmdStationary.Enabled = True
'Change focus from cmdPayments
'in preparation to disable the Command Button
Me.cmdStationary.SetFocus
'Disable cmdPayments Command Button
Me.cmdPayments.Enabled = False
Me.Refresh

End Sub

Download the Demo Database.

You may download the sample databases for a quick view of this trick.


Download Demo SubFormTrick2007.zip

Download Demo SubFormTrick2003.zip

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