Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Updating Combobox when Not in List is Active

Introduction.

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 an error message, requiring them to choose 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

Introduction.

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 usually 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, you will notice that 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 switching between multiple forms dynamically.

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 names of your 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 on 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) through the field SessionID. 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, rather than from 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, not from another subform.

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 then use the name of this TextBox 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 Command Button Click Event Procedures, of Command Buttons: Stationary and Payments, 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:

Form Footer Section Dropping Down Magic

Introduction

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 controls in the newly expanded section.

I attempted to replicate this feature in a Microsoft Access form. Below, you can see screenshots of the form in its normal state and in its expanded state.

In the normal view, observe the bottom portion of the form.


Look at this Form View; the bottom portion of the form is expanded down to display additional options.

Check the following video to see how it works.

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 ultimately stored in tables, while forms are primarily used to display, edit, and save that 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.

  1. Open a new Form in Design View.

  2. Right-click on the Form's Detail Section and select Form Header/Footer to display the Header and Footer Sections of the Form.

  3. Shrink the Footer of the Form so that there is no space showing in the Footer section of the Form.

  4. Select the Header of the Form and display the Property Sheet (F4).

  5. Increase the Height Property value to 0.6”.

  6. Click on the Detail Section and adjust the height of the Detail Section to 2.166”.

  7. 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 a little bigger or smaller, it doesn’t matter.

  8. Create a header label with the caption “CONTROL CENTER” and set the font size to 14, 16, or any size that gives it 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.

  9. Click on the Use Control Wizards button on the toolbar to turn it on if it is not in the selected state.

  10. Select the Options Group and draw a control on the left side of the Form, in the Detail Section, that is big enough to add four lines of options.

    Check the Design View of the Form given below:

  11. Type four Labels one after the other on the control as shown on the design. You can type any labels; this is for design purposes only. 

  12. While the Option Group is in the selected state, display the Property Sheet (F4) and change the Name property value to Frame1.

  13. 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.

  14. Change the Name Property Value of the Options Group control to Frame2.

  15. Change the child label captions to Forms and Reports of Frame1 and Frame2, respectively, and position them above those controls.

  16. Create four Command Buttons, as shown on the design above, and change the Caption Property values to Quit, Open, Print, and More… respectively.

  17. Click on the Quit Command Button to select it.

  18. Display the property sheet (F4) and change the Name property value to cmdQuit.

  19. 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.

  20. Copy and paste the following Code, overwriting the existing lines in the VBA Module.

    The Form Module VBA Code.

    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
  21. If you prefer some changes to the design of the Form, implement them, save and close the Form with the name FormA1.

    Make a Copy of Form A1.

  22. Right-click on FormA1 and select Copy from the Context Menu.

  23. Right-click on the Navigation pane Header and select Paste from the displayed menu.

  24. Change the name of the copy to FormB1.

NB:  I tried to create this trick earlier using a single Form and was not successful at all.  If anybody could do this with a single Form, please share the idea with me.

  1. Open Form B1 in the design view.

  2. Click on the right-most Command Button (with the Caption: More...) and change the caption to …Less.

    Ensure that the position of the command button 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 (check the second image from the top) to give enough space to create a Command Button.

  3. Create a Command Button, at the right side of the footer section, display the property sheet (F4), change the Caption property value to Preview, and change the Name property value to cmdPreview.

  4. Select the On Click Event Property and select [Event Procedure] from the drop-down list, and click the build button (...) to open the VBA Module.

  5. Copy and paste the middle line Code and paste it between Private Sub cmdPreview_Click() and End Sub:

    Private Sub cmdPreview_Click()
        DoCmd.OpenReport "myReport", acViewPreview
    End Sub
  6. Change the report name (myReport) to the name of one of your own Reports.

  7. Press ALT+Q to close the VBA Editing Window.

    You may change the Footer background color to something different, 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:

  1. FormA1 opens through a Macro (macFormA1) at a specific location on the screen.

  2. 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.

  3. 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.

  4. The command button caption changes from More… to Less. Clicking this button reverses the process: FormA1 is reopened at the same coordinates, and FormB1 is closed.

  5. 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 only one form by dynamically expanding and collapsing the footer section with VBA and macros. However, this approach failed to work reliably during repeated actions, and the macros would sometimes not 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 Name of the custom property.  You can use any text value as a name.

  • The dbInteger second parameter is a constant that indicates the custom property Frame1 will store 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; you will end up with errors.  You cannot view the user-defined properties on the Property Sheet of the Form.

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 using a custom property to store data directly on a form.

The Macros.

Now, we have 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.

  1. Select Macro from the Create Menu to open a new macro in the design view.

  2. Add the following Actions and parameters to the macro:

    • Select Echo from the Action column and set 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.

  3. Save and close the Macro with the name macFormA1.

  4. Make a copy of the macro macFormA1 and rename the new macro macFormB1.

  5. Open macro macFormB1 in design view and make only one change in the OpenForm Action line Form Name argument.

  6. Change the Form Name to FormB1.

  7. Save and close the macro.

VBA Code on Both Form Modules.

Now, only two tasks remain to complete the design of both forms:

  1. Copy and paste the two VBA SubroutinesForm_Load() and Form_Unload()—into the VBA modules of both forms.

  2. 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.

  1. Open FormA1 in Design View.
  2. Click on the Command Button with the More… caption to select it.

  3. Press F4 to display the Property Sheet and select On Click Event Property.

  4. Select macFormB1 from the drop-down list of the property.

  5. Press ALT+F11 to display the Form’s VBA editing window.

  6. 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
  7. Save and Close FormA1.

  8. Open FormB1 in Design View.

  9. Click on the Command Button with the caption Less to select it.

  10. Press F4 to display the Property Sheet and select On Click Event Property.

  11. Select macFormA1 from the drop-down list of the property.

  12. Press ALT+F11 to display the Form’s VBA editing window.

  13. Copy and paste the above Subroutines, below the existing Program codes on the module of this Form also.

  14. 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.

  1. Click on the Office Button and select Access Options.

  2. Select Current Database, and select 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.

  3. 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 the On Click event of a command button on another form or by running the macro directly from the Navigation Pane.

To try the trick, we will run the macro macFormA1 directly from the navigation panel.

  1. Display the macros list in the navigation panel.

  2. Double-click on the macro macFormA1 to run it and open FormA1 in Normal view, at the exact location we specified in the macro.

  3. Select any one of the 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 value from both option groups (Frame1 and Frame2) to see the changes reflected on the second form.

  4. Click the More... Command Button to extend the form down to show the Preview Command Button.

  5. 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.

  6. Click on the Preview command button to open your report in print preview.

  7. Click on the Less command button to hide the footer section of the form. This will change the command button caption to More... again.

  8. 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 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), and 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.


Download Demo FormTrick2007.zip
Download Demo FormTrick2003.zip
Share:

PIE Chart and live data on Form

Introduction.

Students' Exam Scores in five different Subjects are recorded in Table: tbl_Students. A sample Table image is given below:

The student’s name from the current record on the form is used as a criterion in a query to filter that student’s exam record. These filtered records are then used as the source data for the Pie Chart displayed on the same form. A sample form with the Pie Chart is shown below:

When any one of the exam records from the five subjects of a student becomes the current record on the form, the Pie Chart should display the marks of all five subjects, along with their percentage of the maximum total marks, on the same form.

This is the tricky part: we cannot directly design a Graph Chart on the form in normal view to filter the query data that serves as the source for the same chart.

Data Source Queries.

To prepare the data for the chart, we need three simple queries to filter and organize the students’ exam records. In addition, a temporary table is required to store the total of all obtainable maximum marks for each subject (for example, 100 × 5 = 500). This value will be used to calculate the percentage of marks obtained in the chart. The image of the temporary table is shown below:



The Three-Part Approach.

We will divide the task into three parts so that the procedure is easy to understand:

  1. Part-A: Create tbl_Students and tmp_MaxMarks.

  2. Part-B: Design Form frm_Students for tbl_Students and creates three simple Queries to prepare the data for Charts.

  3. Part-C: Create a PIE Chart on the frm_Students Form.

Part-A:

  1. Create a table with the same structure shown in the first image at the top, and name it tbl_Students. You may ignore the two empty fields in the table design. As illustrated, the table contains exam scores for three students, each evaluated in five subjects, with a maximum of 100 marks per subject.

  2. Key in those sample data into the tbl_Students Table.

  3. Create a small table with two fields, as shown in the image above, and save it with the name tbl_MaxMarks.

  4. Create a single record with the sample data, shown in the image above.

Part-B:

  1. Design a form in Columnar format based on tbl_Students, leaving enough space on the right side of the form to accommodate the PIE Chart. You can use the Form Wizard to create the Form quickly. Once completed, save the form with the name frm_Students.

    We will create three Queries before working with the Form.

  2. Create the following Queries by copying and pasting the SQL String into the new Query’s SQL Editing Window and saving it with the name as indicated:

    Query-1: StudentsQ

    SELECT [Student] & " " & [Subject] AS [Desc], tbl_Students.Marks
    FROM tbl_Students
    WHERE (((tbl_Students.Student)=[forms]![frm_Students]![student]));
    

    Query-2: MaxMarksQ

    SELECT tmp_MaxMarks.Desc, [MaxMarks]-DSum("Marks","StudentsQ") AS Max_Marks
    FROM tmp_MaxMarks;

    Query-3: UnionPieChart

    SELECT StudentsQ.* FROM StudentsQ
    UNION ALL SELECT MaxMarksQ.* FROM MaxMarksQ;
  3. Open frm_Students in Design View.

  4. Create two TextBoxes below the existing fields.

  5. Click on the first Text box and press F4 to display the Property Sheet.

  6. Change the Name Property value to Obtained.

  7. Type the following expression into the Control Source Property:

    =DSum("Marks","StudentsQ")
  8. Change the Caption Property Value of the Child Label of the Textbox to Total Obtained:.

  9. Click on the second Textbox to select it.

  10. Write the following expression into the control Source Property:

    =[Obtained]/DLookUp("MaxMarks","tmp_MaxMarks")
  11. Change the Format Property Value to Percentage.

  12. Change the Caption Property value of the Child Label of the Text Box to % of Total:.

  13. Save the Form and open it in Normal View.

Let us review what we did so far.

We have created the main table tbl_Students and designed the Form frm_Students, using tbl_Students.

While the frm_Students is active, the StudentsQ data is filtered using the current student's name on the Form as a criterion.

Second Query (MaxMarksQ):

This query sums up the total marks obtained by each student from StudentsQ and compares it against the overall maximum marks (500) stored in tmp_MaxMarks. By subtracting the student’s obtained total from the maximum, we calculate the marks lost.

On the PIE Chart, this difference is represented as a percentage of the total. For example, if the chart shows 10% lost, it means the student secured 90% of the aggregate marks out of 500.

Third Query: UnionPieChart combines the StudentsQ Data and MaxMarksQ queries and is used as a Data Source for the PIE Chart.

Part-C:

Our PIE Chart needs to be displayed on the frm_Students form. However, there’s a challenge:

  • The form must remain open in Normal View so that the selected student’s record can filter the data in StudentsQ.

  • At the same time, a chart object can only be created or embedded on a form when it is in Design View.

This is why we need a small trick to accomplish the task.

Let’s assume the form frm_Students is open, displaying John’s record (the first student). His exam data is already filtered and available through StudentsQ. With this in place, follow these steps to create and embed the PIE Chart into the form:

  1. While keeping the frm_Students in Form View, open a new Form in Design View.

  2. Enable Use Control Wizard Button on the Toolbar above and select Insert Chart Tool from the Controls group.

  3. Draw a Chart in a rectangular shape, large enough to show the formatting (like Value Labels, Title, etc.), like the sample image above.

  4. Select Queries from the View group from the Wizard control and select UnionPieChart from the displayed query list.

  5. Click Next to proceed to the next screen and click on the >> button to select all the displayed fields for the chart.

  6. Click on the PIE Chart Icon to select it and click the Next button twice, then type the following as a heading on the Title control:

    Max. Marks Each=100, 500 Total

  7. Select No, don't display a Legend radio button, then click Finish.

  8. Double-click on the PIE Chart to change it into Edit Mode.

  9. Right-click on an empty area of the chart to display the context menu.

  10. Select Chart Options from the displayed menu.

  11. Select the Data Labels tab and put Check Marks in Category Name, Values, and Percentage.

  12. Click OK to close the control.

    We will reduce the size of the PIE slice labels to smaller font sizes.

  13. Click on one of the PIE slice Labels. This action will select all the Labels together.

  14. Change the Font size to something like 12 points, using the Font/Size Tool above. 

    The completed design of the PIE Chart is given below.

  15. Click outside the Chart Object in the Form to exit from Chart-Edit Mode, but the chart will still be in the selected state.

  16. Right-click on the chart to display the shortcut menu, and click Copy to copy the Chart-Object to the Clipboard.

  17. Save the form with a name and close it if you would like to keep it safe. But we don’t need it anymore.

  18. Now, change the frm_Students into Design View.

  19. Click on the Detail Section of the Form to make the Detail section current.

  20. Right-click on the Detail Section and select Paste from the displayed menu.

  21. Drag the PIE Chart and place it on the right side of the data fields.

  22. Click on the top left corner of the Form and display the Property Sheet (F4) of the Form.

  23. Select the Event Tab of the Property Sheet and click on the On Current property.

  24. Select the Event Procedure from the drop-down list and click on the build (...) Button to open the VBA editing window.

  25. Write the following statement in the middle of the Form_Current() Event Procedure:

    Me.Refresh

    When completed, the procedure will look like the following:

    Private Sub Form_Current()
         Me.Refresh
    End Sub

    When you move the records on the Form, from one to the other, the Form_Current() event procedure will update the record set with the change on the StudentsQ as well.

  26. Close the VBA editing window.

  27. Save the frm_Students Form and open it in Normal View.

The first five records on the Form belong to student John. If you move one record at a time, you will not find any difference on the Chart up to the fifth record, because the values of all five records are shown on the PIE Chart. The sixth to tenth records belong to the second student, and the 11th record onwards belongs to the third student. You may type 6 or 11 on the Record Navigation Control directly to quickly display other students' marks on the PIE Chart.

  1. MS-Access and Graph Charts
  2. MS-Access and Graph Charts-2
  3. Working With Chart Object in VBA
  4. Column Chart and VBA
  5. Pie Chart Object and VBA
  6. Missing Lines in Line-Chart
  7. Pie Chart and Live Data on Form
  8. Scaling Chart Object
  9. Cross-Tab Union Queries for Chart
Share:

External References in Conditional Formatting Expression

Introduction

Normally, we use a Form/Report Text box value in Conditional Formatting expressions to set the Font or Background color of a control.

For example:

FIELD VALUE IS BETWEEN 1 and 10  - whatever formatting you define will be displayed on the selected field, provided the field value is between 1 and 10.

OR

FIELD HAS FOCUS – the conditional formatting becomes visible when the field becomes active.

OR

EXPRESSION IS [ID]=5 OR [LastName] = "Nancy" – formatting is applied to a field, depending on the current values of two other fields used in the expression.

The key values in capital letters are selected from a drop-down control on the Conditional Formatting Dialog Control. We will take the last example of our new method of reference, and let us see how it can be used differently. 

In the above expression, both [ID] and [Last Name] controls are on the same Form/Report and refer to the current record values on the Form/Report.  This is the normal procedure.

A Different Approach

Keep in mind that the values referenced in an expression don’t always have to come directly from the current form or its record source. They can also be pulled from other objects:

From a control on another open form.

From a field in a different table (or query).

When it comes to tables, you don’t need to keep them open to use their values. Instead, you can rely on the DLookup() function, which allows you to fetch a value directly from a table or query field within your expression.

For example:

=DLookup("[MaxMarks]","tmp_MaxMarks")

This will retrieve the MaxMarks value directly from the tmp_MaxMarks table, without opening the table.

This flexibility allows you to combine data from multiple sources—current forms, other forms, and tables—into a single expression that drives your chart or calculation.

When the above example is rewritten with external field reference values, it will look like the expression given below.

EXPRESSION IS Forms![Orders]![OrderID] = Dlookup("Order_ID","tbl_OrderParam")

Assume that the above Conditional Formatting expression is written on a Field (say the Amount field) of frm_myForm.

If the current record OrderID value of Orders Form (the second form in open mode) and the Order_ID value of tbl_OrderParam Table (the expression assumes that the Parameter Table has only one record in it) match, then apply the defined conditional format on the active Form's (frm_myForm) Amount Field.

Try it out yourself and find out how it works.

Earlier Post Link References:

Share:

Storing Bitmap Images in OLEObject Attachments Fields

Introduction.

Microsoft Access provides the OLE Object and Attachment field types to store and display images directly in tables, which can then be shown on forms or reports.

For example:

Storing an employee photo in a staff table.

Storing product images in an inventory table.

However, storing images this way can quickly increase the database size. In Access 2007, bitmap image (.BMP files) placed in an Attachment field are automatically compressed to the size of a JPG, which helps reduce storage overhead—but the database size still grows with every added image.

If your application involves hundreds or thousands of records with images, the file size will expand rapidly, and this becomes a serious limitation. An Access database can only grow to a maximum of 2 GB.

Identifying the Image with its Related Record.

However, if you anticipate this issue in your project, you can plan ahead by storing all required images in a dedicated folder on the disk. Either on a local machine or a network server, depending on user requirements. This approach eliminates concerns about database size. The key, however, is ensuring that each image can be reliably identified and retrieved for its corresponding record, so it can be displayed on forms or reports whenever needed.

Organizing the Images.

It is important to organize images on disk so they can be easily matched with their corresponding records. Once this is properly planned and implemented, retrieving the correct image and displaying it in an Image Control on a form or report becomes straightforward.

The simplest method is to name each image file using a unique field value from the related table, such as the EmployeeID for employee photos (e.g., 1.bmp, 2.bmp, etc.). Similarly, product images can be named using their ProductCode values, ensuring each record is directly linked to its corresponding image.

When a particular employee’s record is current on the Form, we can read the employee code from the form and add the image extension (like Me!ID & “.jpg”) to create the image name, and load it from the disk into an image control on the Form. 

To minimize disk space usage, you can choose image formats that are smaller in size, such as PNG, JPG, or GIF. While GIF images are the smallest, they may compromise image quality. It is best to select a single format, JPG, for example, and save all images in that format. This way, your program can use a simple routine to load the image into an Image Control on a form or report efficiently.

We need only a small Sub-Routine that runs on the Form_Current() Event Procedure to load the picture into the Image control.

Prepare for a Trial Run.

Let us prepare for a trial run of a small Program.

  1. Import the Employees Table from the Microsoft Access Northwind.mdb sample database.

  2. Use the Form Wizard to create a Quick Form in Column Format.

  3. Move or resize the Fields (or remove some unwanted fields) so that we can add an Image Control on the Form, big enough to display sample images, which you will create now.

    A sample Employees Form Design is given below, with the Image Control on it:

  4. Select the Image Control from the Toolbox and draw an Image Control on the Form, as shown above.

  5. Display the Image Control’s Property Sheet (F4) and change the Name Property value to ImgCtl.

  6. Save the Form with the name Employees.

    Note: As I have mentioned earlier, the Employee ID field values are 1, 2, 3, etc. We will create a few images with the names: 1.jpg, 2.jpg, 3.jpg, etc.

    If you were able to import the Employees Table from Northwind.mdb, you are in luck—you already have the employees’ photos stored as bitmap images in the OLE Object field. You can save these images to your disk for use elsewhere. I am using Access 2007, so I will explain the procedure for saving images from the Employees Table to disk in this version. If you are using a different version of Access, the menu options may vary slightly.

    • Open the Employees Table in Datasheet View.

    • Find the Photo field of the first record; the Employee ID of this record is 1.

    • Right-click on the Photo field with the Bitmap Image caption, and select Open from the Bitmap Image Object option.  The image will open in the Paint program.

    • Before saving the image to disk, create a new folder C:\images.

    • Use the Save As… option to save the image in the folder C:\images with the name 1.jpg

    • Save a few more employee photos in this way.

    If you could not save images from the Employees Table, then open any image from your disk in the Paint Program and save it as 1.jpg, 2.jpg, 3.jpg, etc., in the C:\images Folder.

  7. Open the Employees Form (saved in Step 6) in Design View.

  8. Press ALT+F11 to display the VBA Window.

  9. Copy and paste the following code into the VBA Window of the Form, below the Module Global Option: Option Compare Database.

    Private Sub Form_Current()
    Dim strImagePath As String, pic As String
    On Error GoTo Form_Current_Err
    'image folder
    strImagePath = "c:\images\"
    'create image name
    pic = Me![ID] & ".jpg"
    strImagePath = strImagePath & pic
    'validate image name and location
    If Len(Dir(strImagePath)) > 0 Then
    'image found, load it into the image control
      Me!ImgCtl.Picture = strImagePath
    Else
    'image not found, make image control empty.
      Me!ImgCtl.Picture = ""
    End If
    
    Form_Current_Exit:
    Exit Sub
    
    Form_Current_Err:
    'Not necessary to display a message here
    Resume Form_Current_Exit
    End Sub
  10. Save and close the Form.

    The Trial Run.

  11. Open the Form in Normal View.

    If everything went well, then you will see the first employee photo in the image control.  The Sample Screenshot of  the Employees Form with the photo is given below:

  12. Use the record navigation control to move to the next record and display other images.

Image Display on Report.

A sample Employees' Report Design, with Image Control, is given below.

  1. Design a Report using a few fields from the Employees table, as shown above, and see that you are using the Employee [ID] Field on the Report.  This is important because we need this number to create the image name corresponding to the record in print.

  2. Insert the Image Control on the Report, as shown in the above Image.

  3. Display its Property Sheet and change the Name Property value to ImgCtl.

  4. Click somewhere on the empty area of the Detail Section of the Report.  If you have closed the Property Sheet, then press F4 to display it.

  5. Select the On Format Event Property and click on the build (...) Button to open the VBA Window of the Report.

  6. Copy and paste the following code and replace the Detail_Format() Event procedure opening and closing statements:

    Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)
    Dim strImagePath As String, pic As String
    On Error GoTo Detail_Format_Err
    'image folder
    strImagePath = "c:\images\"
    'create image name
    pic = Me![ID] & ".jpg"
    strImagePath = strImagePath & pic
    'validate image name and location
    If Len(Dir(strImagePath)) > 0 Then
    'if found load the image into the image control
      Me!ImgCtl.Picture = strImagePath
    Else
    'make image control empty.
      Me!ImgCtl.Picture = ""
    End If
    
    Detail_Format_Exit:
    Exit Sub
    
    Detail_Format_Err:
    'Not necessary to display a message here
    Resume Detail_Format_Exit
    
    End Sub
  7. Save the Report and close it.

    The Trial Run of the Report.

  8. Open the Report in Print Preview.

    The Sample Report Preview is given below:

If you want to give more flexibility to your project, with all four image types (bmp, png, jpg, and gif), then you may use the following modified Code:

Private Sub Form_Current()
Dim strImagePath As String, pic As String
Dim strImagePathName As String, strI(0 To 3) As String
Dim j As Integer, strType As String

On Error GoTo Form_Current_Err

strI(0) = ".bmp"
strI(1) = ".png"
strI(2) = ".jpg"
strI(3) = ".gif"

strImagePath = "c:\images\"
pic = Me![ID]

strType = ""
For j = 0 To UBound(strI)
  strImagePathName = strImagePath & pic & strI(j)
  If Len(Dir(strImagePathName)) > 0 Then
     strType = strI(j)
     Exit For
  End If
Next
  
strImagePathName = strImagePath & pic & strType

If Len(strType) > 0 Then
  Me!ImgCtl.Picture = strImagePathName
Else
  Me!ImgCtl.Picture = ""
End If

Form_Current_Exit:
Exit Sub

Form_Current_Err:
'Not necessary to display a message here
Resume Form_Current_Exit

End Sub

Note: The Report must be in Print-Preview mode to view the images in the Report. The Images may not appear in Layout View.

Share:

Opening External Access Report inside Active Database

Introduction.

Last week, we explored how to print a Report from another MS Access database. Using a VBA program, we created a separate MS Access Application Window, opened the external database within that window, and printed a report from it. To accomplish this, we used the Application.DoCmd.OpenReport command to open the report in Print Preview. The same code was also used within Excel (in a macro-enabled workbook) to preview the same MS Access report.

However, the procedure was somewhat complicated and not easy to follow—especially if you are not very familiar with VBA.

Fortunately, if you only need to print a report or open a Form from an external MS Access database within your current database, there is a much simpler way.

By following the procedure explained below, you can open a report from another database directly in your current database window, either in Print Preview or Print mode, depending on how you configured it. With the same approach, you can also open forms just as easily.

Simple Preparations.

The procedure goes something like the following:

First, let us define the names of databases, reports, and Forms involved in this procedure, for reference.

  • Current Database Name: DatabaseA.mdb

  • Second Database Name: DatabaseB.mdb

  • Report to Print Preview from DatabaseB.mdb: myReport.

  • Form to open from DatabaseB.mdb: myForm.

  1. Open DatabaseB.mdb (you may select any database you have, with at least one Report and one Form).

  2. Open the VBA Editing Window (ALT+F11).

  3. Insert a new Standard Module (Insert -> Module).

  4. Copy and paste the following VBA Code into the Module:

    Public Function myReportOpen()
    'Replace myReport with your own Report name in quotes.
       DoCmd.OpenReport "myReport", acViewPreview
    End Function

    Calling the above VBA Function from DatabaseA.mdb will open myReport from DatabaseB.mdb and will appear in DatabaseA Application Window, in Print Preview.

  5. Copy and paste the following VBA Code below the earlier Function myReportOpen():

    Public Function myFormOpen()
     'Replace myForm with your own Form Name
       DoCmd.OpenForm "myForm", acViewNormal
    End Function

    We have created two simple functions in DatabaseB and ensured that DatabaseA does not have functions with the same name.

  6. Save the VBA Module with the functions and close DatabaseB.mdb.

  7. Open DatabaseA (any database you would like to see the Report/Form open from DatabaseB.mdb).

  8. Open VBA Editing Window (ALT+F11).

    The Reference Library Usage.

  9. Select Tools -> References.

    You will see the VBA References Dialog box as shown below, with a lengthy list of available Library Files and the files already selected for the current project, with checkmarks, on top of the list.  You must browse and find DatabaseB.mdb from its parent folder, select it, and click Open to attach it to the current database as a Library File.

  10. Use the Browse... button on the References Dialog Box, find DatabaseB.mdb from its folder, and open it. See that you have selected 'Microsoft Access Databases' in the Files of Type control; otherwise, Database file names will not appear.

    The selected Database's Project Name (must be different from your database name) will appear at the bottom of the Library Files list.

  11. Click OK to close the Dialog Box.

    Now, the functions myReportOpen() and myFormOpen() of DatabaseB are visible in DatabaseA. It means that you can call those functions from DatabaseA.mdb to open myReport or myForm from DatabaseB.mdb and display them in DatabaseA Window.

    How It Works.

    Note: When the Function myReportOpen() is called from DatabaseA.mdb, it will first check for myReport in DatabaseB (the parent database of the function). If the report exists there, it will open from 'DatabaseB' and display in the current database. If not, the function will then search for the report with the same name in DatabaseA.mdb and open it from there.

    Keep this behavior in mind when working with library functions. By design, they look for referenced objects in the library file first. This feature can be useful when you are creating custom wizards or designing shared forms that need to work seamlessly across multiple databases.

    At this point, you can test the programs by running them from the Debug Window.

  12. Press CTRL+G to display the Debug Window (Immediate Window) if it is not already visible.

  13. Type the following command in the Debug Window and press Enter Key:

    myReportOpen

    The report will open in Print Preview mode behind the VBA window. To view it, simply minimize the VBA window. You can also test the myFormOpen() function to confirm that it works in the same way. For convenience, consider creating two command buttons on a form and assigning these functions to their Click event procedures, so you can run them directly from the form without opening the VBA editor each time.

    Opening Form/Report of DatabaseB from DatabaseA

  14. Open a form and create two Command Buttons on it.

  15. Select the first command button and display its Property Sheet (F4).

  16. Change the Name Property value to cmdReport.

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

  18. Click on the build button (...) at the right end of the property to open the VBA Window.

    You will find the opening and closing lines of a Subroutine, similar to the program lines given below, except for the middle line.

    Private Sub cmdReport_Click()
       myReportOpen
    End Sub
  19. Copy the centerline of the above procedure and paste it into the middle of the VBA subroutine.

  20. Similarly, name the second Command Button to cmdForm and follow the same steps (16 to 19) to create the following Sub-Routine in the VBA Window.

    Private Sub cmdForm_Click()
       myFormOpen
    End Sub
  21. Save the Form.

  22. Open the Form in normal view, click on the Command Button(s) to open myReport/myForm from DatabaseB.mdb.  The user of your database will not know whether the Report is opening from the library database or from the active database.

Earlier Post Link References:

Share:

Printing Ms-Access Report from Excel

Introduction.

Printing an MS Access Report from Excel or from Another Database

In Microsoft Access applications, we often use a Front-End/Back-End design. All the tables are maintained in the Back-End database and linked to the Front-End. We link them because the Front-End frequently needs to retrieve or update data from those tables.

Once linked, external database tables behave just like native tables in the Front-End. You can work with them seamlessly, without noticing any difference.

Note: When linking tables from a network location, always use the full UNC path of the database file, for example:

\\ServerName\FolderName\SubfolderName\DatabaseName.mdb

Instead of a server-mapped drive path, such as:

T:\FolderName\SubfolderName\DatabaseName.mdb

This is important because if the mapped drive letter (e.g., T:\) changes later to K:\, Z:\, or another letter, the links will break. Using the full network address ensures the linked tables remain intact regardless of drive mappings.

Updating a Table not Linked with the Current Database.

When you need to retrieve (or add/update) information in a table that is not linked to the front-end database, we need a VBA program to do that.

A sample procedure is shown below:

Public Function CategoryTable()
Dim wsp As Workspace, db As Database
Dim rst As Recordset

'Set a reference to the active Workspace
Set wsp = DBEngine.Workspaces(0)

'DBEngine.Workspaces(0).Databases(0) is CurrentDB 
'Open a second database in Workspace(0).Databases(1) position 
Set db = wsp.OpenDatabase("C:\mdbs\NWSample.mdb")
 
'Open Categories recordset from Database(1) 
Set rst = db.OpenRecordset("Categories")
 
'Display the CategoryName field value 
MsgBox rst![CategoryName]
 
rst.Close 
db.Close 

'remove objects and release memory
Set rst = Nothing 
Set doc = Nothing 
Set db = Nothing 
Set wsp = Nothing 
End Function

The Databases Workspace.

Working with Databases in the DBEngine Workspaces Collection

When an Access database is opened in the Application Window, it is actually opened within a Workspace in the Workspaces collection, under the Application.DBEngine object.

The default Workspace is Workspace(0).

The first open database inside that workspace is addressable as Workspaces(0).Databases(0).

You can open more than one database within the same workspace and work with its tables or query recordsets. This approach is often better than permanently linking those tables to the Front-End database, especially if you do not need to use them on a day-to-day basis.

⚠️ However, there is an important limitation: you cannot open Forms or Reports from databases opened this way.

In fact, the object reference:

Application.DBEngine.Workspaces(0).Databases(0)

is equivalent to the CurrentDb object. While several databases can be loaded into Workspaces(0), only the current database will be visible in the Access Application Window. Other databases, if opened, will remain in memory until you explicitly close them.

This means you can:

Read and update tables from an external database without linking them together.

Create new tables or queries in those external databases as needed.

But you cannot:

Open forms or reports stored in those databases through this method.

Creating Queries on a non-linked External Table.

What if we want to create a query using data from an external table that is not linked to the front-end database? Surprisingly, Microsoft Access allows you to create queries without permanently linking external tables to the current database. Curious about how this works? You can learn the trick [here].

Up to this point, our discussion has focused on working with external tables and queries. However, the methods we covered so far will not allow you to open a form or report from another database. Normally, this requires opening the database in a separate Access Application Window.

That said, this statement is not entirely accurate—we’ll explore why in next week’s session.

But before diving into the Excel-based procedure, let’s first see how the same task can be handled from the active database itself.

The simple procedure steps are given below:

  1. Create a separate Access Application Object.

  2. Set its visible property value to Yes, so that we can see the Application Window.

  3. Open the required Access Database within that Application Window.

  4. Open the required Report in Print-mode (acViewNormal) to send the Report directly to the default printer, or in Print-Preview-mode (acViewPreview) to view the report before sending it to the printer manually.

  5. Close the Database first and Quit the Application.

The Sample VBA Code is given below:

' Include the following in Declarations section of module.
Dim appAccess As Access.Application

Public Function PrintReport()
'---------------------------------------------------------
'Original Code Source: Microsoft Access Help Document
'---------------------------------------------------------

    Dim strDB As String

' Initialize string to database path.
    Const strConPathToSamples = "C:\Program Files\Microsoft Office\Office11\Samples\"
    strDB = strConPathToSamples & "Northwind.mdb"

' Create new instance of Microsoft Access Application.
    Set appAccess = CreateObject("Access.Application")
' Make Application Window Visible
    appAccess.Visible = True

' Open database in Microsoft Access window.
    appAccess.OpenCurrentDatabase strDB

' Open Catalog Report in Print Preview
    appAccess.DoCmd.OpenReport "Catalog", acViewPreview
    
' Enable next line of code to Print the Report
    'appAccess.DoCmd.OpenReport "Catalog", acNormal

    'appAccess.DoCmd.Close acReport, "Catalog", acSaveNo
    'appAccess.CloseCurrentDatabase
    'appAccess.Quit
    
End Function
  1. Copy and paste the above code into a new Standard Module of your Database.

  2. Make changes to the Path of the Database and Report name, if needed.

  3. Click somewhere in the middle of the Code and press F5 to run the Program.

In Microsoft Excel.

If you were able to run the code successfully and Print/preview your Report in a separate Access Application Window, then you may proceed to do the same thing from Microsoft Excel.

  1. Open Microsoft Excel.

  2. Display VBA Window (Developer ->Visual Basic).

  3. Insert a Standard Module (Insert -> Module) in the VBA Window.

  4. Copy and paste the above Code into the Module and save it.

Before running the code, you must add the Microsoft Access 12.0 Object Library to the Excel Project.

  1. Select the References option from the Tools Menu.

  2. Find Microsoft Access 12.0 Object Library (or whatever version is available on your machine) and put a check mark to select it.

  3. Click the OK Command Button to close the Control.

  4. Click in the middle of the Code and press F5 to run.

You will see the same result you saw when you ran the Code in Microsoft Access.

  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:

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 Class Module External Links Queries Array msaccess reports Accesstips WithEvents msaccess tips Downloads Objects Menus and Toolbars Collection Object MsaccessLinks Process Controls Art Work Property msaccess How Tos Combo Boxes Dictionary Object ListView Control Query VBA msaccessQuery Calculation 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 RaiseEvent Recordset Top Values Variables Wrapper Classes msaccess email progressmeter Access2007 Copy Excel Export Expression Fields Join Methods Microsoft Numbering System Records Security Split SubForm Table Tables Time Difference Utility WScript Workgroup 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 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