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:
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.
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:
Create an Access Application Object and open it.
Open the target database within the Access Application.
Keep the Access Application window hidden.
Open the target table from the Database.
Count the rows in one of the Excel data columns.
Open a loop to write the Excel data one row at a time, starting from the second row onward.
Repeat the writing action till all the rows are transferred to the Access Table.
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.
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.
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.
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.
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.
Right-click on the Report Footer bar and select Properties to display the Property Sheet.
Select the Height Property and change the property value to 0.33” or 0.838 cm.
Select the Text Tool from the Toolbar above and draw a text box on the Report Footer area below the Product Sales column.
Write the expression =Sum([ProductSales]) in the Control Source property of the text box. Change the Name property value to SubTotal.
Modify the Caption property value of the child label to read as Sub-Total.
Save and close the Sales by Category Subreport.
The Main Report Changes.
Open the Sales by Category main report in Design View.
Create a TextBox on the Header Section of the Report, to the right of the report heading.
While the text box is in selected state, display the property sheet (F4).
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=TotalSalesSubTotal×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.
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.
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
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 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.
Next time you want to do something like this, you can do it in a few minutes.
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:
Display Text: the text that appears in a field or control, indicating the hidden link's purpose
Address: external file's path-name
Sub-Address: Internal Object Name, to open Form, Report, etc.
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.
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.
Create a table with a single field and data type Hyperlink.
Save the table with a name.
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
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.
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.
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.
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.
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:
Prepare the Customers' source data in a SELECT Query for the report.
Open a new report in Design View.
Insert the SELECT Query name into the Record Source Property of the Report.
Use the Data Grouping and Sorting option of the Report to organize and display A, B, C, etc., in the Group Header.
Design the Report.
Preview the Report.
A Sample Report.
Sample alphabetized list of customers. Report Preview is given below:
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.
Click OK to open the selected Access Database and expose its Tables, Queries, Reports, etc.
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.
Click on the Create menu and select Query Design from the Other group.
Click the Close button to close the Show Table Dialog Box without selecting any object from the displayed list.
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.
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.
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.
Select the Data Tab on the Property Sheet.
Click the Record Source Property, and click the drop-down list at the right end of the property.
Find CustomerListQ Query (use the slider, if necessary) and select it from the drop-down list to insert it into the Record Source property.
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.
Click the Add a Group control displayed in the Group, Sort, and Total shown below the empty report.
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.
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.
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.
Select the TextBox control and draw a text box on the Alpha Header Section of the report.
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.
Select the child label of the text box and delete it.
Create another text box in the Report Detail Section, below the Alpha Header control.
Select the CName Column name from the drop-down list in the Control Source property under the Data Tab in the TextBox Property Sheet.
Reduce the Detail Section height by dragging the Page-Footer section to the height of the TextBox.
Save the Report as Customer List.
Print Preview the Report.
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.
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:
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].
Close archive.accdb database.
Open the Back-End Database.
Transfer only the Structure of tblMaster into the Archive.accdb
Create a SELECT Query on tblMaster with an appropriate criterion to select the old data.
Open the SELECT Query in Datasheet View, take the total record count, and note it down.
Change the SELECT Query into an Append Query.
Save and run the Append Query to transfer the selected data directly to the Table tblMaster in Archive.accdb.
Close the BE database and open the Archive database.
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.
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.
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-ListEvent Procedure of the cboProd Combo box.
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:
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.
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.
Change the Name Property Value of the Child Label to HeaderLabel.
Create an Option Group Control above the sub-form with the existing three form names as Labels.
Change the Name Property value of the Options Group Control to Frame1.
Change the Default Value property value of the Options Group Control to 0.
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.
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
Modify the above Code to replace the Form Names in quotes with your own form names.
Press ALT+Q to close the VBA Window.
Change the Child-label Caption of the Options Group control to Form Selection.
Save and close the Form.
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 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:
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.
This method has always fascinated me, especially after seeing it in other applications. It works like this:
When you open a dialog form, it initially presents a few options to choose from. In addition, the dialog often includes a Command Button labeled Advanced..., or More..., indicating that additional options are available. When you click this button, the Form extends downward, revealing more Options in the newly expanded section.
I attempted to replicate this feature in a Microsoft Access Form. You can see screenshots of the Form in its normal and expanded state below.
In the normal view, observe the bottom portion of the form.
Now that you understand our goal, we will design two forms, create two macros, and write a few small procedures in the forms’ VBA modules. This project also demonstrates how to create and use custom properties on a form—beyond the standard properties visible in the Property Sheet—to store values directly on the form and retrieve them when needed.
Keep in mind that data is always stored in tables, while forms are primarily used to display, edit, and save data back to the table. You might not have considered that you can store values on the form itself—though not as extensively as in a table—but this approach allows for several clever techniques and shortcuts. Links to previously published articles on this topic are provided at the end of this page for reference.
The Design Task.
Open a new Form in Design View.
Right-click the Form's Detail Section and select Form Header/Footer to display the Header and Form Footer Sections.
Shrink the Form Footer, and there is no space in the Form Footer Section.
Select the Form Header and display the Property Sheet (F4).
Increase the Height Property value to 0.6”.
Click on the Detail Section and adjust the height of the Detail Section to 2.166”.
Click on the left top corner of the Form (or select Form from the Selection Type control – Access 2007) to select the Form’s Property Sheet and change the Width property value to 4.875”.
Note: If your Form size is bigger or smaller, it doesn’t matter.
Create a header label with the caption “CONTROL CENTER” and set the font size to 14, 16, or any size that gives a clear heading appearance. To add a subtle 3D effect, copy the label and place the duplicate slightly above and to the right of the original. Then, change the font color of the original label to a lighter shade—this will create a visually appealing layered effect for the heading.
Select the Use Control Wizards button on the Toolbar.
Select the Options Group, draw a control on the Form's left side in the Detail Section that is big enough to add four lines of options.
Type four Labels one after the other on the control as shown in the design. You can type any labels; this is for design purposes only.
While the Option Group is selected state, display the Property Sheet (F4) and change the Name property value to Frame1.
Create another Option Group control on the right side of the earlier one and add four items. Give the third label caption to the name of a Report in your database.
Change the Name Property Value of the Options Group control to Frame2.
Change the child label captions to Forms and Reports Frame1 and Frame2, respectively, and position them above those controls.
Create four Command Buttons, as shown on the design above, and change the Caption Property values to Quit, Open, Print, and More… respectively.
Click on the Quit Command Button to select it.
Display the property sheet (F4) and change the Name property value to cmdQuit.
Select the On Click Event property and select [Event Procedure] from the drop-down list, and click on the Build Button (...) to open the VBA Module of the Form.
Copy and paste the following Code, overwriting the existing lines in the VBA Module.
Option Compare Database
Option Explicit
Dim db As Database, doc As Document
Private Sub cmdQuit_Click()
On Error GoTo cmdQuit_Click_Err:
Me![Frame1] = 1
Me![Frame2] = 1
DoCmd.Close acForm, Me.Name
cmdQuit_Click_Exit:
Exit Sub
cmdQuit_Click_Err:
MsgBox Err & " : " & Err.Description, , "cmdQuit_Click()"
Resume cmdQuit_Click_Err
End Sub
If you prefer some changes to the Form design, implement them, save and close the Form named FormA1.
Make a Copy of Form A1.
Right-click on FormA1 and select Copy from the Context Menu.
Right-click on the Navigation pane Header and select Paste from the displayed menu.
Change the Form copy name to FormB1.
NB: I tried to create this trick using a single Form earlier but couldn't succeed. If anybody could do this with a single Form, please share the idea with me.
Open Form B1 in the design view.
Click on the right-most Command Button (with the Caption: More...) and change the caption to …Less.
Ensure that the CommandButton position remains exactly the same. If you’re unsure, compare the Left and Top property values with those of the command button on FormA1. If they differ, update them to match FormA1. Do not make any other changes to the Detail or Header sections of Form B1. The goal is for FormB1 to be an exact clone of FormA1 before incorporating any additional features.
Expand the Footer Section down (the second image from the top) to give enough space to create a Command Button.
Create a Command Button on the right side of the footer section, display the property sheet (F4), change the Caption property to Preview, and change the Name property to cmdPreview.
Select the On Click Event Property, select [Event Procedure] from the drop-down list, and click the Build button (...) to open the VBA Module.
Copy and paste the middle line of code, paste it between Private Sub cmdPreview_Click() and End Sub:
Private Sub cmdPreview_Click()
DoCmd.OpenReport "myReport", acViewPreview
End Sub
Change the report name (myReport) to the name of one of your own Reports.
Press ALT+Q to close the VBA Editing Window.
You may change the Footer background color, or leave it as it is.
How it Works.
By now, you probably understand that we need two nearly identical forms to create this user interface trick. Here’s how it will be presented to the user:
FormA1 opens through a Macro (macFormA1) at a specific location on the screen.
Both forms must open at the same screen coordinates to give the appearance of a seamless transition. They are identical in size and design, except that FormB1 has its footer section extended with an additional command button.
When the user clicks the command button labeled More…, a second Macro (macFormB1) opens FormB1 directly on top of FormA1 and simultaneously closes FormA1. The transition is so fast that the user perceives it as if the footer section of FormA1 simply drops down to reveal the new button.
The CommandButton caption changes from More… to Less. Clicking the button reverses the process: FormA1 is reopened at the same coordinates, and FormB1 is closed. The only visible animation is the Form Footer Section extending downward, restoring the form to its original state.
The Preview command button opens a report, providing additional functionality without breaking the illusion of a single, expanding form.
I initially attempted to achieve this effect using a single form by dynamically expanding and collapsing the Footer Section with VBA and macros. However, this approach did not work reliably when the actions were repeated, and the macros would sometimes fail to execute as expected.
The Option-Group Issues.
We need a one-time run of a program to create the custom properties Frame1 and Frame2 on Form A1. Copy and paste the following program into a new Standard VBA Module:
The Custom Property Creation.
Public Function createProperty()
Dim db As Database, doc As Document
Dim prp1 As Property, prp2 As Property
Set db = CurrentDb
Set doc = db.Containers("Forms").Documents("FormA1")
Set prp1 = doc.CreateProperty("Frame1", dbInteger, 1)
Set prp2 = doc.CreateProperty("Frame2", dbInteger, 1)
doc.Properties.Append prp1
doc.Properties.Append prp2
doc.Properties.Refresh
Set doc = Nothing
Set prp1 = Nothing
Set prp2 = Nothing
Set db = Nothing
End Function
Click somewhere in the middle of the Code, and press F5 to run the program to create the Frame1 and Frame2 Custom properties on form FormA1. The CreateProperty() method accepts three parameters.
The first parameter, "Frame1," is the custom property Name. You can use any text as a name.
The dbInteger second parameter is a constant that indicates the custom property Frame1 accepts Integer Type data.
The third parameter is the initial value stored in the custom property Frame1.
Two custom properties are created and appended to the properties collection.
Don't run the above program a second time; it will produce errors. You cannot view the user-defined properties on the Form's Property Sheet.
We don’t have to create these custom properties on the other form: FormB1.
Container and Document Objects.
Note: In the program above, the collection of Forms is referred to as a Container Object. Other examples of container objects include Tables (Queries also fall under Tables), Reports, and Scripts (Macros).
Each container object consists of multiple Documents. For instance, every form you create is treated as a document within the Forms container. Similarly, tables, reports, and macros appear as documents under their respective containers.
These are just a few examples of container objects—there are others as well. To explore the complete hierarchy of Access objects, properties, and methods, refer to the Access Object Model Reference in VBA Help and select Object Model Map from the Table of Contents.
For a practical example, you may also check our previously published method: [Saving Data on Forms Not in a Table], which demonstrates a custom property and stores data directly on a form.
The Macros.
Now, we need to create two Macros to control the open/close events of FormA1 and FormB1. With macros, we can define where exactly the form should appear on the Screen.
Select Macro from the Create Menu to open a new macro in the design view.
Add the following Actions and parameters to the macro:
Select Echo from the Action column, and set it to No in the Echo On parameter in the Arguments column.
Select OnError from the Action column in the next row and set Next in the Go to Argument.
Select Close from the Action column in the next row and select Prompt in the Save Argument.
Select OpenForm from the Action column in the next row and set FormA1 in the Form Name control, set Form in the View argument, and set Normal in the Window Mode argument.
Select MoveSize from the Action column in the next row and set the values 1”, 1”, 4.875” in the Right, Down, and Width arguments, respectively.
Save and close the Macro named macFormA1.
Make a copy of the macro macFormA1 and rename the new macro macFormB1.
Open macro macFormB1 in design view and make only one change in the OpenForm Action line Form Name argument.
Change the Form Name to FormB1.
Save and close the macro.
VBA Code on Both Form Modules.
Now, only two tasks remain to complete the design of both forms:
Copy and paste the two VBA Subroutines—Form_Load() and Form_Unload()—into the VBA modules of both forms.
Assign the macros we created earlier to the On Click events of the command buttons labeled More… and …Less.
Once these steps are completed, the forms will be fully functional with the interactive expand/collapse behavior.
Open FormA1 in Design View.
Click on the Command Button with the More… caption to select it.
Press F4 to display the Property Sheet and select the On Click Event Property.
Select macFormB1 from the Property drop-down list.
Press ALT+F11 to display the Form’s VBA editing window.
Copy and paste the following Sub-Routines below the existing Program codes on the module:
Private Sub Form_Load()
'Load values from the custom properties of FormA1
'into Frame1 and Frame2
On Error GoTo Form_Load_Err
Set db = CurrentDb
Set doc = db.Containers("Forms").Documents("FormA1")
Me!Frame1 = doc.Properties("Frame1").Value
Me!Frame2 = doc.Properties("Frame2").Value
Me.Repaint
Form_Load_Exit:
Exit Sub
Form_Load_Err:
MsgBox Err & " : " & Err.Description, , "Form_Load()"
Resume Form_Load_Exit
End Sub
Private Sub Form_Unload(Cancel As Integer)
'Before closing the Form, save the Option selections
'of the User into the custom properties
On Error GoTo Form_Unload_Err
Set db = CurrentDb
Set doc = db.Containers("Forms").Documents("FormA1")
doc.Properties("Frame1").Value = Me!Frame1
doc.Properties("Frame2").Value = Me!Frame2
doc.Properties.Refresh
Form_Unload_Exit:
Exit Sub
Form_Unload_Err:
MsgBox Err & " : " & Err.Description, , "Form_Unload()"
Resume Form_Unload_Exit
End Sub
Save and Close FormA1.
Open FormB1 in Design View.
Click on the Command Button with the caption Less to select it.
Press F4 to display the Property Sheet and select the On Click Event Property.
Select macFormA1 from the Property drop-down list.
Press ALT+F11 to display the Form’s VBA editing window.
Copy and paste the above Subroutines below the existing Program on the module of this Form also.
Save and Close Form B1.
Test Running the Project.
Now, it is time to test our form footer drop-down trick. But before we open the forms, we must change some Global settings of Microsoft Access.
Click on the Office Button and select Access Options.
Select Current Database, and select the Overlapping Windows Radio Button under Document Window Options.
A message is displayed to close Microsoft Access and open it again to take effect the new settings.
Restart Microsoft Access and open your database.
If FormA1 is opened directly from the Navigation Pane, it may not appear at the exact location specified in the macros (i.e., 1″ from the top and 1″ from the left of the window). To ensure it opens in the correct position, always run the first macro, macFormA1, either from a CommandButton Click event procedure from another form or run the macro from the Navigation Pane.
To try the trick, we will run the macro macFormA1 directly from the Navigation Pane.
Display the macros list in the Navigation Pane.
Double-click on the macro macFormA1 to run it and open FormA1 in Normal view, at the exact location we specified in the macro.
Select any options from the Reports Option Group.
Remember, we have attached one of your Reports to the Preview command button’s OnClick event procedure just to verify that the report runs from there. At this stage, we are not performing any validation on the Reports Option Group to determine which option the user has selected. I asked you to select an option only to observe how the selected value is transferred to the second form, Form B1. You can choose any option from both the Option Group controls (Frame1 and Frame2) to see the changes reflected on the second form.
Click the More... Command Button to extend the form down to show the Preview Command Button.
Check whether the selected report option appears on Form B1 in the Reports Option Group also. The command button with the More... caption is now changed to …Less.
Click on the Preview command button to open your report in print preview.
Click on the Less command button to hide the footer section of the form. This will change the command button caption to More... again.
Click on the Quit Command Button to close the Form and the Report also.
Well, how’s that for a trick? After all, it’s all about surprising the user right before their eyes. From the user’s perspective, they won’t have a chance to catch the action in slow motion or figure out how it really works.
This is all about two simple Forms of Magic.
I realize this was a lengthy explanation, but at its core, it’s all about using two forms with nearly identical designs, displayed one after the other in the same location. You also learned how to store program parameter values directly on the form itself—a powerful feature that can be leveraged to create many clever effects. For another example of this, see our earlier trick: Create Your Own Color Palette.
I’m not sure about later versions of Access (I’m still using Access 2007), whether they offer any simpler methods to achieve the same effect.
Download Demo Database
You may download the sample database from the Links given below.