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

Showing posts with label msaccess controls. Show all posts
Showing posts with label msaccess controls. Show all posts

Limit to List Combo Box

Introduction.

Combo Boxes in tables and forms are used to quickly insert frequently used values into data fields. The source data for a combo box can come from a table, a query, or a value list. To use it, the User clicks the drop-down arrow to display the available options and selects the required value. Alternatively, the user can also type in values directly into the combo box control.

However, one important property setting determines how the combo box behaves:

  • The first setting restricts the user to selecting only from the existing list and prevents invalid values in the target field.

  • Limit to List = Yes

  • On Not in List = [Event Procedure]

When the Limit to List property is set to Yes, you can only select or type values that already exist in the combo box list. Any manually entered values that are not in the list will be rejected. To use a new value, it must first be added to the source table (or query/value list) that supplies data to the combo box.

Example:

Suppose you have a table containing a list of fruits with only two items: Apple and Cherry. This list is used as the source for a combo box on a Sales Form. If the Limit to List property is set to Yes, you cannot type Orange directly into the field. Instead, you must first add Orange to the fruit table; only then will it appear as a valid option in the combo box.

The On-Not-in-List Event.

When the On Not in List Property is set to an Event Procedure, it is executed when the user enters a new value (Orange) manually into the Control-Source Field of the Combo Box. We can write code in the Event Procedure to add the entered new value into the Combo Box Source Table directly (after taking confirmation from the User) and update the Combo Box on the Form.

This method saves the time that would otherwise be spent opening the combo box’s source table and manually adding new items. In addition, values added directly to the source table do not automatically refresh the contents of the combo box.

Let us try this out using the above example items as Source Data.

Combo Box Row Source Table.

  1. Create a new Table with a single Field Name: Fruit and select the Data Type Text.

  2. Save the Table Structure and name it Fruitlist.

  3. Open the Table in Datasheet View and key in Apple and Cherry as two records.

  4. Close and save the Table with the records.

  5. Create another table with the following Structure:

    Table Structure
    Field Name Data Type Size
    ID AutoNumber
    Description Text 50
    Quantity Numeric Long Integer
    UnitPrice Numeric Double
  6. Before saving the Structure, click on the second Field Data Type (Text) Column to select it.

  7. Click on the Lookup Tab on the Property Sheet below.


    Combo Box Property Settings.

  8. Click on the Display Control Property and select Combo Box from the drop-down control.

  9. The Row Source Type Property Value will be Table/Query; if it is not, then select it from the drop-down control.

  10. Click on the drop-down control of the Row Source Property and select the Table Fruit list from the displayed list of Tables.

  11. Change Column Width Property and List Width Property Values to 1".

  12. Change the Limit to List Property Value to Yes.

  13. Save the Table Structure with the name Sales.

  14. Open the Table in Datasheet View and add a new record with Apple, 100, and 1.5 in Description, Quantity, and UnitPrice Fields, respectively.

  15. Close and save the Table with the record.

  16. Click on the Sales Table to select it and select Form from the Insert Menu.

  17. Create a Form using the Form Wizard in Column Format and save the Form with the name Sales.

    Testing Settings.

  18. Open the Sales Form in the normal view.

    Since we have added the Combo Box to the Table Structure, it already appears on the form.

  19. Press Ctrl++ (or click on the New Record control on the Record Navigation control) to add a new blank record on the Form.

  20. Click on the drop-down control of the Combo Box and you will find the list of fruits: Apple and Cherry in it.

  21. But, you Key-in Orange into the Description field and press Enter.

    You will be greeted with the following error message:

    If you want to enter the value Orange on the Form, first you must add that item to the Fruit list Table.

  22. To add a new item, open the Fruit List table, enter Orange as a new record, and then close the table.

However, this action will not automatically refresh the combo box contents to include Orange in the list. To see the updated value, you must either close and reopen the Sales form or add a command button to the form and write code that requeries the combo box contents.

What we did manually in response to the above error message can be automated by writing a VBA Routine that can be run through the On Not in List Event Procedure. You don't need to close and open the Form to refresh the Combo Box contents either.

Add New Item through VBA

  1. Open the Sales Form in Design View.

  2. Click on the Description Field to select the Combo Box control.

  3. Display the Property Sheet (View -> Properties).

  4. Find and click on the On Not in List Property.

  5. Select Event Procedure from the drop-down list.

  6. Click on the build button (. . .) To open the VBA Module.

  7. Copy and paste the following Code into the Module, overwriting the top and bottom Procedure lines already appearing in the Module:

    Private Sub Description_NotInList(NewData As String, Response As Integer)
    Dim strmsg As String, rst As Recordset, db As Database
    
    If Response Then
        strmsg = "Entered Item not in List!" & vbCr & vbCr & "Add to List...?"
          If MsgBox(strmsg, vbYesNo + vbDefaultButton2 + vbQuestion, "Not in List") = vbYes Then
           Set db = CurrentDb
           Set rst = db.OpenRecordset("FruitList", dbOpenDynaset)
           rst.AddNew
           rst![Fruit] = NewData
           rst.Update
           rst.Close
           Me.Description.Undo
           Me.Description.Requery
           Me![Description] = NewData
           Me.Refresh
        End If
        Response = 0
    End If
    End Sub
  8. Save and Close the Sales Form.

    Trial Run Program.

  9. Open it in a normal view.

  10. Now, type the name of any fruit that is not in the Combo Box list (say, Peach) in the Description field.

    You will be greeted with the following Message Box:

  11. Click the Command Button with the LabelYes, to add the new item keyed in the Description Field into the Fruit List Table and refresh the Combo Box List automatically.

  12. Now, click on the drop-down control of the Combo Box, and you can see that the new item is added to the list and accepted in the Description Field as well.

Share:

Menus with Option Group Control

Introduction

We can create cascading menus on a form using Tab Controls and Option Group controls. Multiple menus can be arranged neatly, one behind the other, allowing the user to select the main menu option to display the corresponding submenu.

For example, the sample image below illustrates a Main Menu with three options, each representing a different category, along with a corresponding group of sub-menu Options for each category.

When the Data Files option is selected in the main menu, the corresponding Submenu appears on the right, allowing the user to click any option to open and work with that file.

Similarly, selecting Reports in the main menu displays the report options in the same area, replacing the previously shown data file options. Choosing the Views option brings up its respective sub-menu, again replacing the previous display.

In this way, multiple menus can be arranged and transitioned in the same space with a seamless, dynamic interface. These menus can be programmed using VBA or macros to run the detailed options associated with each selection.

Simple Interface Design and Code

You don't need to work with any complicated VBA Programs except a few simple lines of Code and Macros. The design task is simple, and once you know the trick, you can implement it anywhere in no time.

The sample Design image of the above Form is given below:

  1. Open a new Form in the Design view.

  2. Select the Option Group Control from the Toolbox and draw it near the left side of the Form in the Detail Section.

  3. Enter the three Options (Data Files, Reports, and Views), pressing the Tab Key in each step to advance to the next line in the Wizard.

  4. Click Finish to create the Option Group Control with Radio Button type Controls, with the Keyed-in Values as Labels.

  5. Change the Caption Value of the attached child label to Main Menu and position it on top of the Options Group control in the design above.

  6. Click on the outer frame of the Options Group Control to select it and display its Property Sheet (View -> Properties).

  7. Change the Name Property Value to Frame0 and the Border color Property Value to 0.

  8. Select the Tab Control from the Toolbox and draw a Tab Control to the right of the Options Group Control (check the design image above).

    A Tab Control with two Pages will be created.  We must insert one more Page into the Tab Control.

  9. While the Tab Control is still in the selected state (if it is not, then click on the right of the Tab Pages), Right-Click on it to display the Shortcut Menu.

  10. Select Insert Page from the Shortcut Menu to add another Page to the Tab Control.

  11. While the Tab Control is still in the selected state, display its Property Sheet.

  12. Change the Name Property Value to TabCtl9.

    NB: No dot (.) at the end of the name when you change it on the control.

    Data Tables Menu.

  13. Click on the First Page of the Tab Control to make it current.

  14. Select Option Group Control from the Toolbox and draw it on the First Page of the Tab Control.

  15. Enter the following Options (or Form Names of your own Tables in your Database) by pressing the Tab Key after each option on the Wizard:

    • Employees
    • Orders
    • Order Details
    • Customers
    • Products
  16. Click Finish to complete and create an Option Group with Radio Button Style options.

  17. Display the Property Sheet of the Options Group (View ->Properties).

  18. Change the following Property Values as shown below:

    • Name = Frame1
    • Default Value = 0
    • Border Color = 0
  19. Change the Caption of the Child-Label attached to the Options Group Control to Data Files, make its width as wide as the Option Group Control, and position it above, as shown in the design image above.

    We must create two Option Group Controls on the 2nd and 3rd Pages of the Tab Control with a different set of Options.

    The Reports Menu.

  20. Follow Steps 13 to 19 to create Option Group Control on the 2nd Page of the Tab Control with the following options and name the Option Group Frame as Frame2 and the Child-Label Caption as Report List:

    • Employee Address Book
    • Employee Phone Book
    • Invoice
    • Monthly Report
    • Quarterly Report

    Create Report Names from your own Database, replacing the above List.

    Data View Menu.

  21. Create another Option Group Control on the 3rd Page of the Tab Control with the following options, or create your own Options and name the Option Group as Frame3 and Child-Label Caption as View Options:

    • View Inventory
    • View Orders
    • View Customers
    • View Suppliers

    Now, we have to write a few lines of VBA Code for the Main Menu Option Group to select the detailed Options Page of the Tab Control based on the menu selection. Even though Page Captions show something like Page10, Page11, and Page12 (this may be different on your design), each Page is indexed as 0, 1, and 2. If you want to select the second Page of the Tab Control to display the Report Options, then you must address the Tab Control Page2 in Code as TabCtl9.Pages(1).Setfocus.

    We can select an individual Page of the Tab Control by clicking on it too.  But, this manual action will not synchronize with the Main Menu selection. The items on the Option Group Menu also have the index numbers from 1 to the number of items on the Menu (Report List options 1 to 5).

    When the user clicks on one of the items on the Option Group Main Menu, we can test its index number and make its corresponding detailed menu on the Tab Control Page current.

    In the final refinement of the Menus, we will hide the Tab Pages of the Tab Control so that the Sub-Menus on them can be accessed only through the program, depending on the selection made on the Main Menu by the User.

    Code for Main Menu.

    First, a small VBA Routine on the On Click Event Procedure of the Frame0 Option Group Control (Main Menu) to allow the user to select one of the options on it and display its corresponding detailed Sub-Menu on the Tab Control. By default, 1st item (Data Files) on the Main Menu will be in the selected state, and the Data Files list will be visible on the Sub-Menu.

  22. Display the Code Module of the Form (View -> Code) or click on the Module Icon on the Toolbar Button.

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

    Private Sub Frame0_Click()
    Dim k
    k = Me![Frame0]
    Select Case k
        Case 1
            Me.TabCtl9.Pages(0).SetFocus
        Case 2
            Me.TabCtl9.Pages(1).SetFocus
        Case 3
            Me.TabCtl9.Pages(2).SetFocus
    End Select
    
    End Sub

    Trial Run of Menu.

  24. Save and close the Form with the name Main Switchboard.

  25. Open the Main Switchboard in a normal view.

  26. Click on the 2nd Option Reports on the Main Menu to display the Report List on the 2nd Page of the Tab Control.

  27. Try selecting other options on the Main Menu, and monitor the Submenu changes on the Tab Control Pages.

Forms Menu.

Now, we will write VBA Code similar to the above example to open Data File Forms when the User selects Options from the Sub-Menu.

  1. Open the Main Switchboard in Design View.

  2. Display the Code Module of the Form (View ->Code).

  3. Copy and paste the following VBA Code into an empty area of the Module:

    Private Sub Frame1_Click()
    Dim f1
    f1 = Me![Frame1]
    Select Case f1
        Case 1
            DoCmd.OpenForm "Employees", acNormal
        Case 2
            DoCmd.OpenForm "Orders", acNormal
        Case 3
            DoCmd.OpenForm "Order Details", acNormal
        Case 4
            DoCmd.OpenForm "Customers", acNormal
        Case 5
            DoCmd.OpenForm "Products", acNormal
    End Sub
  4. Save and Close the Main Switchboard Form.

    Macros for Report Menu.

    To run the Report Options, we will create a Macro and attach it to the Options Group Control (with the name Frame2) rather than using the VBA routine.

  5. Select the Macro tab in the Database window and select New to open a new Macro in the design view.

  6. You must display the Condition Column of the Macro by selecting the Toolbar Button with the Icon Image (or similar image) given below:

  7. Write the following Macro lines, as shown in the image given below, with the appropriate Parameter Values at the bottom Property Sheet for opening each Report in Print Preview/Print:

  8. Save the Macro with the name RptMac.

    Attach Macro to Report Options.

  9. Open the Main Switchboard Form.

  10. Click on the 2nd Page of the Tab Control to display the Reports Option Group Menu.

  11. Click on the outer frame of the Options Group Menu to select it.

  12. Display the Property Sheet (View ->Properties).

  13. Find and click on the On Click Property to select it.

  14. Click on the drop-down list at the right edge of the Property and select the RptMac name from the list to insert it into the On-Click Event Property.

     NB: You may create another Macro/VBA Routine for the third menu and attach it to the Frame3 Option Group Menu, before doing the next step.

    In the next step, we will remove the pages of the Tab Control. Transitions between tab pages can be controlled entirely through code. This creates a seamless, “magical” effect for the sub-menu, allowing different menus to appear interchangeably in the same location.

    You can further refine the sub-menus by adjusting their dimensions and positions. Ensure to apply the same settings consistently to all three sub-menus on the Tab Control pages for a uniform appearance.

    • Top
    • Left
    • Width
    • height
  15. Click on the outer edge of the Tab Control (or click on the right side of the third page) to select it.

  16. Display the Property Sheet (View ->Properties).

  17. Find the Style Property in the Property Sheet and change the value of Tabs to None.

  18. Save and close the Main Switchboard Form.

  19. Open the Form in normal view and try out the Menu.

Share:

Microsoft Date Time Picker Control

Microsoft Date Time Picker Control.

In an earlier article, Animated Floating Calendar, we learned how to use the Calendar Control to simplify Date Entry form fields. In that method, a single calendar control was used for multiple date fields by automatically moving it near the selected field with a smooth unfolding animation.

This approach helps to save space on the Form; otherwise, we would need to place separate calendar controls for each date field.

Now, we have an even better alternative — the Microsoft Date and Time Picker (DTPicker), an ActiveX control that closely resembles a Combo Box and is extremely easy to use.

Learn its Simple Usage.

Let us try a simple example to learn how to use this Calendar for a Date Field on a Form.

  1. Import the following Objects from C:\Program Files\Microsoft Office\Office11\Samples\Northwind.mdb sample database:

    • Table: Employees
    • Form: Employees
  2. Open the Employees Form in Design View.

  3. Select the Company Info Tab.

  4. Select the ActiveX Control option from the Insert Menu.

  5. Select the Microsoft Date and Time Picker Control from the displayed list and click OK to create a control on the Form.

  6. Move the control near the HireDate Field and resize it as shown in the sample design of the Form given below:

    Few Simple Rules of Date/Time Picker Control.

    • Before using the Date and Time Picker control with date fields, it’s important to understand a few simple rules.

      You can set the Control Source property of the Date and Time Picker to a field, such as HireDate, and remove the existing HireDate text box from the form.

      However, note that the HireDate field cannot be blank. If you navigate to a record where the HireDate field is empty, or if you try to add a new record without assigning a date, the control will display the following error message:

      “Can’t set the value to NULL when CheckBox property = FALSE.”

    This error message indicates that the HireDate field cannot be left blank, and you also cannot clear the date value from the field once it has been set—unless the CheckBox property of the Date and Time Picker control is set to Yes.

    Important Settings.

  7. First things first—make sure the Date and Time Picker control you added to the form is selected. Then, open the Property Sheet (by choosing View → Properties or pressing Alt + Enter) and make the following changes:

    • Set the Control Source property to HireDate.

    • Set the CheckBox property to Yes.

    When you navigate to a record, the Date and Time Picker will automatically display the date stored in the HireDate field. To change the existing hire date, simply move the calendar to the desired year and month, then click the required date.

    If you move to a record where the HireDate field is NULL, the check mark will disappear, and the field will appear disabled, indicating that it’s empty. However, the control may still display the date from the previously accessed record. If you open the calendar drop-down, that previous date will automatically populate the HireDate field. You can either remove the check-mark to clear the field or select a new date from the calendar to overwrite the value.

    If you prefer to adjust the date manually—by incrementing or decrementing the day, month, or year like you would on a digital clock—set the UpDown property to Yes. This changes the calendar’s drop-down into a spin button control, replacing the standard calendar view.

    Once enabled, click any date segment (day, month, or year), and use the spin buttons to increase /decrease the value to your desired setting.

  8. You can experiment with the Date and Time Picker control, keeping the points mentioned above in focus, to better understand how the calendar behaves under different settings.


    Settings for Time Value.

  9. If you want to enter time values instead of dates using the Date and Time Picker control, change its Format property value to 2. This automatically sets the UpDown property to Yes, replacing the drop-down calendar with a spin button control. You can then use the spin buttons to adjust each segment of the time value — hours (hh), minutes (mm), seconds (ss), and AM/PM — individually, just as explained earlier.


Share:

Web Browsing within Access Form

Web Browsing within an Access Form.

Browsing the World Wide Web is nothing new to us. But how about organizing the web addresses of frequently visited websites in a table and browsing the web directly from an Access form?

Not only can you browse Internet sites, but you can also access Intranet websites within your local corporate LAN. To do this, simply create an Access form with a Microsoft Web Browser Control and add a few lines of VBA code.

For example, the following VBA code will automatically open the Gmail website (http://www.gmail.com/ When the form containing the Web Browser Control is opened, as illustrated in the image above:

Simple Website Opening Code.

Private Sub Form_Load()
Dim strURL As String

strURL = "http://www.gmail.com/"
Me.WebBrowser0.Navigate strURL
End Sub

Designing a Form for a Web ActiveX Control.

Don't know how to do it? Try the following:

  1. Open a new Form in Design View.

  2. Click somewhere on the Detail Section of the Form to select that area.

  3. Select the ActiveX Control from the Insert Menu.

  4. Look for the name Microsoft Web Browser in the displayed list of ActiveX Controls and select it.

  5. Click OK to insert a Web Browser Control on the Form.

  6. While the Control is still in the selected state, drag the bottom-right-corner sizing control to make it big enough on the Form so that you can view the Web Pages properly.

  7. Display the Property Sheet of the Browser Control (View ->Properties).

  8. Change the Name Property Value to WebBrowserO to match the name used in the above VBA Code.

  9. Select Code from the View Menu to display the VBA Code Module of the Form.

  10. Copy and Paste the above Code into the Module.

  11. Save and close the Form named myWebBrowser.

    Demo Run of the Form.

  12. Connect your PC to the Internet.

  13. Open the myWebBrowser Form in normal View.

  14. Wait a few seconds for the Web Page to load in the Control and to display.

In the previous example, we used the website address directly in the code. However, if you create a table containing all the websites you visit frequently, you can use a combo box on the form to select a website and navigate to it quickly. To achieve this flexibility, you will need to make a few modifications to the code above.

Table with Frequently Visited Web Addresses

  1. Create a Table with a single field with the following details:

    Table Name: Websites

    Field Name: Web Address Data Type: Text Field Size: 255

  2. Save the Table Structure and open it in Datasheet View.

  3. Add a few records with Web URLs that you visit frequently, and save and close the Table.

  4. Make a copy of the Form myWebBrowser and name it myWebBrowser2.

  5. Open myWebBrowser2 in Design View.

  6. Display the Form Header Section (View -> Form Header/Footer), if it is not already Visible.

  7. Expand the Form Header Section with enough height to create a Combo Box Control.

  8. Create a Combo Box using the Web Sites Table.

  9. While the Combo Box is still in selected state, display the Property Sheet (View -> Properties).

  10. Change the following Property Values of the Combo Box:

    • Name: cboWeb
    • Width: 5"
    • Default Value: "http://www.gmail.com/" or any other Website Address Value you prefer.
  11. Select the child label attached to the Combo box and change the Caption Property Value to Web Address:

  12. Display the Code Module of the Form (View -> Code).

  13. Copy and paste the following Code into the Module, replacing the existing lines.

    Form Module Code

    Option Compare Database
    Option Explicit
    
    Dim WebObj As WebBrowser
    Dim varURL As Variant
    
    Private Sub cboWeb_Click()
         GotoSite
    End Sub
    
    Private Sub cboWebLostFocus()
         GotoSite
    End Sub
    
    Private Sub Form_Load()
         Set WebObj = Me.WebBrowser0.Object
         GotoSite
    End Sub
    
    Private Function GotoSite()
        varURL = Me!cboWeb
    If Len(Nz(varURL, "")) = 0 Then
        Exit Function
    End If
    
    WebObj.Navigate varURL
    
    End Function
  14. Save the Form and open it in Normal View.

  15. The website address that you have inserted into the Default Value Property of the Combo Box will open up in the Browser Control.

  16. Select one of the other website addresses you have added to the Table from the Combo Box.

  17. The Browser Window will open the new Website.

If we open other Web Pages by selecting the Links from the displayed page, then we can navigate between pages by adding a few more lines of code.

Review of the VBA Code.

But first, let’s examine the code above to understand how it works. We have declared a Web Browser object variable and a Variant variable in the Module's global declaration section.

Created a separate Function, GotoSite(), to respond to different Events (Actions) on the Form without duplicating the code everywhere.

For example, when we open the Form, the GotoSite() Function opens the Default Value URL we set in the Combo Box Property through the Form_Load() Event Procedure.

When you select a URL from the Combo Box, the cboWeb_Click() Event Procedure calls this Function to open the Web Page in the Browser.

If you type a URL in the Web Address control cboWeb and move the Cursor out of the control, the Lost_Focus() Event Procedure runs the Function to open the URL you typed in the Address Control.

We will create a few Command Buttons in the Header of the Form, as shown to the right of the Combo box Control in the above design, and write Subroutines using simple Browser Object Commands to navigate between Web Pages, which we may open from the displayed Web Pages.

Web Navigation Controls.

  1. Open the myWebBrowser2 Form in Design View.

  2. Display the Toolbox (if it is not visible, then select Toolbox from the View Menu.

  3. Create five Command Buttons to the right of the Combo Box.

  4. Display the Property Sheet of the first Command Button and change the Name Property and Caption Property Values to Home.

  5. Similarly, change the Name and Caption Property Values of the other Command Buttons with the values given below.

    • Back
    • Forward
    • Refresh
    • Stop
  6. Display the Code Module of the Form (View ->Code), copy and paste the following code into the VBA Module, below the existing Code lines.

Private Sub Home_Click()
On Error Resume Next
    WebObj.GoHome
End Sub

Private Sub Back_Click()
On Error Resume Next
    WebObj.GoBack
End Sub

Private Sub Forward_Click()
On Error Resume Next
    WebObj.GoForward
End Sub

Private Sub Refresh_Click()
On Error Resume Next
    WebObj.Refresh
End Sub

Private Sub Stop_Click()
On Error Resume Next
     WebObj.Stop
End Sub

The On Error Resume Next Statement prevents Subroutines from running into an uncontrolled Error when there are no Web Pages to navigate to.

To test these Buttons, you must click on a few links on the displayed Web Page to open other Pages from the same website and then use these buttons to navigate between those opened pages.

The Home Button will open the Default Home page you set in Internet Explorer's Tools -> Internet Options... Home Page -> Address Control, not the default value you set in the Combo Box in the Browser control.

Share:

Form Bookmarks And Data Editing-3

Continued on Form Bookmarks.

This is the continuation of our discussion on Form Bookmarks to revisit the records visited earlier. The links to the earlier Articles are given below:

  1. Form Bookmarks And Data Editing
  2. Form Bookmarks And Data Editing-2

The discussion on Bookmarks would be incomplete without exploring how to search for and locate records using the RecordsetClone property.

In our earlier examples, we used the Find control (Ctrl+F or Edit → Find...) to locate a record and, once found, stored its Bookmark in an array variable for later use.

This time, we’ll take a different approach — we’ll find the record and bring it directly into view on the Form by using the Bookmark of the form’s RecordsetClone.

For this method, we will use an Unbound Text Box to enter the search key and a Command Button click to find the record. To keep the VBA Code simple, this time we will use the Customers table rather than the Order Details table because the Order Details Table has several records with the same OrderIDs.

When we use the Order Details table, we need to establish a relationship between ProductID and OrderID to create a unique Key and find a specific record among several records within the same OrderID. This method was already used in the earlier example, which displays all the records we have retrieved and edited.

Review of Bookmarks.

As mentioned in earlier articles, when a Form is opened with a Table, Query, or SQL statement as its Record Source, each record displayed on the Form is assigned a unique identification tag by MS Access known as a Bookmark.

We can create a copy of this recordset in memory—called a RecordsetClone—and work with it independently of the Form. Using this RecordsetClone, and with the Form’s Bookmark attached to each record, we can locate any desired record through VBA code using a specific search key value. Once the target record is found in memory, its Bookmark can be read and assigned to the Form’s Bookmark property, making that record the current one displayed on the Form.

However, it’s important to note that this relationship works only in one direction: you cannot read the Form’s Bookmark property value and use it to locate the same record within the RecordsetClone.

The Ease of Usage.

From the User's Point of View, enter the Search Key-Value (CustomerID) into the Unbound Text Box and click the Command Button next to it to find that record and bring it up on the Form.

Look at the sample VBA Code given below that runs on the Command Button Click (with the Name cmdFind) after setting the Search Key-Value (CustomerID) in an Unbound Text Box with the name xFind.

Private Sub cmdFind_Click() 
Dim m_Find, rst As Recordset
m_Find = Me![xFind]
Set rst = Me.RecordsetClone
rst.FindFirst "CustomerID = '" & [m_Find] & "'"
If Not rst.NoMatch Then 
     Me.Bookmark = rst.Bookmark 
End If

End Sub

The line that reads Set rst = Me.RecordsetClone copies the Form's Recordset into the Recordset Object Variable rst in Memory, and the next line runs the FindFirst method of the Recordset Object to search and find the record with the given CustomerID Value.

In the next three lines, we are testing whether the 'rst.FindFirst' method was successful in finding the record or not. If found, then the Bookmark of the current record in the Recordset is transferred to the Bookmark Property of the Form to make that record Current on the Form.

There is an article on this method posted a few months ago, titled: Animating Label on Search Success. You may visit that Page to copy the complete VBA Code of the subroutine given above and try it out.

You must import the Customers Table and Customers Form from the C:\Program Files\Microsoft Office\Office11\Northwind.mdb sample Database and modify the Form to add a Text Box and a Command Button at the Footer of the Form.

The 'rst.FindFirst' statement finds the record and becomes current; a Label at the bottom of the Unbound Text Box will flash a few times with a message indicating that the search operation was successful and the record is current on the Form. If the search operation failed, then the Label will flash a few times with the message: Sorry, not found.

This method, added to the above program, gives the User a quick indication of whether the search was successful. To visit the Page and try it out, click here.

Earlier Post Link References:

Share:

Form Bookmarks And Data Editing-2

Continued from Bookmarks and Data Editing

In the first part of this article, we used saved Bookmarks to revisit previously accessed records, allowing us to review and verify the accuracy of any edited information.

The function myBookMarks() we created for this purpose can be enhanced with an additional option—in addition to the existing options: 1 = Save Bookmark, 2 = Retrieve Bookmarks, 3 = Initialize Bookmark List—to display all the edited records together in Datasheet View.

However, this approach comes with certain side effects that must be understood before implementation. Recognizing these potential issues early will help you design effective workaround strategies when necessary. In this section, we’ll explore these challenges using the Order Details table as an example.

In the previous example, we used the Bookmark index number along with the OrderID value to verify that the correct records were being retrieved.

In many cases, a single purchase order may include multiple products, and consequently, all the records related to that order will share the same OrderID. If we use only the OrderID as a criterion in a query, it will return several Products associated with that order, regardless of which specific record we had previously visited.

This limitation didn’t arise when we relied on Bookmarks, since each record has a unique Bookmark that precisely identifies it. In those earlier cases, the OrderID served merely as a reference point to verify that the retrieved record is the correct one.

However, our current approach uses the OrderID values saved in the Combo Box list as query criteria to retrieve all edited records at once. This can lead to unwanted duplicates or ambiguous results.

We can overcome this issue by ensuring that each item in the Combo Box list represents a unique record. If the table already has a unique field (such as a primary key), we can use that instead of the OrderID. Otherwise, we can combine multiple field values to create a unique identifier for each record, and store this composite value in the Combo Box list,  along with the Bookmark index number.

This enhancement will form the basis of the fourth option in the myBookMarks() function.

Unique ID Value(s) as Key.

We will now combine the OrderID and ProductID values and store them together in the ComboBox list. Since the same product code will never appear more than once in a single purchase order, this combination guarantees that each entry in the ComboBox represents a unique record.

The purpose of this new approach is to dynamically generate a query based on the ComboBox contents, allowing us to display all edited records from the Order Details table with a single click.

In the fourth option of the myBookMarks() function, we will build an SQL statement using the combined OrderID–ProductID values as query criteria. This SQL string will then replace the SQL of a pre-defined SELECT query, enabling it to retrieve the corresponding records.

To trigger this functionality, we’ll add another CommandButton beside the << Reset button. When the user clicks this button, all the edited records are displayed in Datasheet View.

Before proceeding, let’s write the code segment that implements this specific option. We’ll begin by declaring the required objects and variables in the declaration section of the function.

Dim db as Database, QryDef as Querydef
Dim strSql as String, strSqltmp as String, strCriteria as a String
.
.
.
Select Case ActionCode
.
.
.
Case 1
.
Case 2
.
Case 3
.
Case 4

strSqltmp = "SELECT [Order Details].* "
strSqltmp = strSqltmp & "FROM [Order Details] "
strSqltmp = strSqltmp & "WHERE ((([OrderID]" & "&" & Chr$(34)
strSqltmp = strSqltmp & "-" & Chr$(34) & "&" & "[ProductID]) In ('"

strCriteria = ""
For j = 0 To ArrayIndex -1
   If Len(strCriteria) = 0 Then
   strCriteria = ctrlCombo.Column(1, j)
Else
   strCriteria = strCriteria & "','" & ctrlCombo.Column(1, j)
End If

Next

strCriteria = strCriteria & "')));"

Set db = CurrentDb
Set Qrydef = db.QueryDefs("OrderDetails_Bookmarks")
strSql = strSqltmp & strCriteria
Qrydef.SQL = strSql
db.QueryDefs.Refresh
DoCmd.OpenQuery "OrderDetails_Bookmarks", acViewNormal
End Select 

We begin by defining the static portion of the SQL statement in the variable strSqltmp. Next, we loop through the items in the Combo Box, extracting the values from its second column, which contains the combined OrderID and ProductID separated by a hyphen (-). Inside the 'For… Next' loop, these values are used to build the criteria string in the variable strCriteria.

Once the criteria are fully constructed, we redefine the SQL statement of the OrderDetails_BookMarks query, inserting the newly built criteria before opening the query to display the extracted records.

Remember that Combo Box columns in Access use zero-based indexing. This means that the second column is referenced as Column(1, j), where j is the current row index. The statement

strCriteria = strCriteria & "-,'" & ctrlCombo.Column(1, j) 

therefore retrieves the combined OrderID–ProductID string value from the second column and appends it to the criteria string used for record selection.

Modified VBA Code.

The modified Code of the myBookMarks() Function with the above Option is given below.

  1. You may copy the Code and paste it into the Standard Module, replacing the earlier code, or rename the earlier Function and save this Code separately, with the original name.

    Public Const ArrayRange As Integer = 25
    Dim bookmarklist(1 To ArrayRange) As String, ArrayIndex As Integer
    
    Public Function myBookMarks(ByVal ActionCode As Integer, ByVal cboBoxName As String, Optional ByVal RecordKeyValue) As String
    '-----------------------------------------------------------------
    'Author : a.p.r. pillai
    'Date   : October-2009
    'URL    : www.msaccesstips.com
    'Remarks: All Rights Reserved by www.msaccesstips.com
    '-----------------------------------------------------------------
    'Action Code : 1 - Save Bookmark in Memory
    '            : 2 - Retrieve Bookmark and make the record current
    '            : 3 - Initialize Bookmark List and ComboBox contents
    '            : 4 - Filter Records and display in Datasheet View
    '-----------------------------------------------------------------
    Dim ctrlCombo As ComboBox, actvForm As Form, bkmk As String
    Dim j As Integer, msg As String, bkmkchk As Variant
    Dim strRowSource As String, strRStmp As String, matchflag As Integer
    Dim msgButton As Integer
    
    Dim db As Database, Qrydef As QueryDef
    Dim strSql As String, strSqltmp As String, strCriteria As String
    
    'On Error GoTo myBookMarks_Err
    
    If ActionCode < 1 Or ActionCode > 4 Then
       msg = "Invalid Action Code : " & ActionCode & vbCr & vbCr
       msg = msg & "Valid Values : 1 to 4"
       MsgBox msg, , "myBookMarks"
       Exit Function
    End If
    
    Set actvForm = Screen.ActiveForm
    Set ctrlCombo = actvForm.Controls(cboBoxName)
    Select Case ActionCode
        Case 1
            bkmk = actvForm.Bookmark
            'check for existence of same bookmark in Array
            matchflag = -1
            For j = 1 To ArrayIndex
               matchflag = StrComp(bkmk, bookmarklist(j), vbBinaryCompare)
               If matchflag = 0 Then
                   Exit For
               End If
            Next
            If matchflag = 0 Then
               msg = "Bookmark of " & RecordKeyValue & vbCr & vbCr
               msg = msg  & quot;Already Exists."
               MsgBox msg, , "myBookMarks()"
               Exit Function
            End If
            'Save Bookmark in Array
            ArrayIndex = ArrayIndex + 1
            If ArrayIndex > ArrayRange Then
              ArrayIndex = ArrayRange
              MsgBox "Boookmark List Full.", , "myBookMarks()"
              Exit Function
            End If
            bookmarklist(ArrayIndex) = bkmk
    
            GoSub FormatCombo
    
            ctrlCombo.RowSource = strRowSource
            ctrlCombo.Requery
        Case 2
            'Retrieve saved Bookmark and make the record current
            j = ctrlCombo.Value
            actvForm.Bookmark = bookmarklist(j)
        Case 3
            'Erase all Bookmarks from Array and
            'Delete the Combobox contents
            msg = "Erase Current Bookmark List...?"
            msgButton = vbYesNo + vbDefaultButton2 + vbQuestion
            If MsgBox(msg, msgButton, "myBookMarks()") = vbNo Then
                Exit Function
            End If
            For j = 1 To ArrayRange
               bookmarklist(j) = ""
            Next
            ctrlCombo.Value = Null
            ctrlCombo.RowSource = ""
            ArrayIndex = 0
        Case 4
            strSqltmp = "SELECT [Order Details].* "
            strSqltmp = strSqltmp & "FROM [Order Details] "
            strSqltmp = strSqltmp & "WHERE ((([OrderID]" & "&" & Chr$(34)
            strSqltmp = strSqltmp & "-" & Chr$(34) & "&" & "[ProductID]) In ('"
            strCriteria = ""
            For j = 0 To ArrayIndex - 1
                If Len(strCriteria) = 0 Then
                    strCriteria = ctrlCombo.Column(1, j)
                Else
                    strCriteria = strCriteria & "','" & ctrlCombo.Column(1, j)
                End If
            Next
            strCriteria = strCriteria & "')));"
     
           Set db = CurrentDb
            Set Qrydef = db.QueryDefs("OrderDetails_Bookmarks")
            strSql = strSqltmp & strCriteria
            Qrydef.SQL = strSql
            db.QueryDefs.Refresh
            DoCmd.OpenQuery "OrderDetails_Bookmarks", acViewNormal
    End Select
    
    myBookMarks_Exit:
    Exit Function
    
    FormatCombo:
    'format current Bookmark serial number
    'and OrderID to display in Combo Box
    strRStmp = Chr$(34) & Format(ArrayIndex, "00") & Chr$(34) & ";"
    strRStmp = strRStmp & Chr$(34) & RecordKeyValue & Chr$(34)
    
    'get current combobox contents
    strRowSource = ctrlCombo.RowSource
    
    'Add the current Bookmark serial number
    'and OrderID to the List in Combo Box
    If Len(strRowSource) = 0 Then
         strRowSource = strRStmp
    Else
         strRowSource = strRowSource & ";" & strRStmp
    End If
    Return
    
    myBookMarks_Err:
    MsgBox Err.Description, , "myBookMarks()"
    Resume myBookMarks_Exit
    End Function

  2. A Select Query and some Changes in the Form.

    You can test this new option by making a few minor changes to the Form we created earlier (see the design view image below). To begin, create a Command Button and a simple SELECT Query that we’ll use to display the bookmarked records.

    First, create a new Query with the following SQL statement and save it under the name OrderDetails_BookMarks:

    SELECT Order Details].*
    FROM Order Details];
    

    Next, open the Order Details Form in Design View and add a new Command Button next to the existing (<) Button, as shown in the sample Form design below. This new button runs the procedure that retrieves and displays the edited records from the Order Details table in Datasheet View.

  3. Click on the newly added Command Button to select it, and open the Property Sheet by choosing View → Properties from the menu.

    In the Property Sheet:

  • Set the Name property to cmdShow.

  • Set the Caption property to View Records.

  • Next, locate the On Click property. From its drop-down list, select [Event Procedure], and then click the Build (…) button. This will open the Form’s Code Module, where Access automatically inserts the empty procedure skeleton, as shown below:

    Private Sub cmdShow_Click()
    
    End Sub
    
  • Write the middle of the Sub-Routine as shown below:

    Private Sub cmdShow_Click()
        myBookMarks 4, "cboBMList"
    End Sub
    

Perform a Trial Run

  1. Save and close the Order Details Form and open it in Normal View.

  2. Double-click on the Record Selector of a few records on the Form to add the Bookmark List to the Combo Box.

  3. Click on the drop-down control of the Combo Box to ensure that the selected Item Codes are added to the Combo Box List.

  4. Click on the View Records Command Button to open the Query OrderDetails_Bookmarks in Datasheet View with the records that match the Combo Box Values.

  5. Examine the sample image displaying the Query result overlapping the Form, all records corresponding to the values stored in the Combo Box list.

    Notice that the Product field displays the Product Description instead of the Product Code that appears in the Bookmark Combo Box on the main form. This is because the Display Width of the Combo Box’s first column (Product Code) is set to 0", effectively hiding it from view in Datasheet mode. However, when you select an item from this Combo Box, the Product Code—not the description—is stored in the Order Details table, since it is the bound column.

    When you double-click a record selector, the stored ProductID value (rather than the displayed description) is retrieved and combined with the OrderID value to update the Combo Box list correctly.

    Let us find out how to open a Form with the last record you were working on in an earlier session: Click here.

    Want to find out how to use Combo Boxes and List Boxes in different ways? Visit the following Links:

    1. Selected ListBox Items and Dynamic Query
    2. Create a List from another ListBox
    3. ListBox and Date: Part-1
    4. ListBox and Date: Part-2
    5. ComboBox Column Values
    6. External Files List in Hyperlinks
    7. Refresh Dependent ComboBox Contents
Share:

Form Bookmarks and Data Editing

Form Bookmarks and Data Editing.

Assume that you are about to edit information on 25 records in the Form, selected at random by searching for their ID keys. To begin, open the main data editing Form and use the Find control (Ctrl+F) to search for each record by entering its key value (for example, Employee Code or OrderID). Once the record is found, make the necessary edits. You’ll need to repeat this process for all 25 records the first time, as this is the only way to locate and modify them.

However, since the information you’ve changed is critical, even a small mistake could cause serious issues. Errors can easily slip in when working quickly. Therefore, it’s essential to review each record again to verify that all edits are accurate.

Unfortunately, repeating the same search-and-edit process for all 25 records—opening the Find dialog, typing the key values, and clicking Find Next each time—is far less appealing the second time around.

But what if you could revisit all those records—one by one, in the exact order you edited them—without repeating the entire cumbersome search process? That would certainly make the verification task much faster and easier.

I emphasized the term in the same order because you’ll likely have your source document or change log arranged in the sequence you first edited the records.

To make this possible, we’ll develop a simple yet powerful technique using the Form’s Bookmarks feature. This method will help application users navigate and review their edited records effortlessly.

FORM BOOKMARKS.

When you open a Form that’s linked to a Table, Query, or SQL statement, each record on that Form is automatically assigned a unique identifying tag by MS Access, known as a Bookmark (a two-byte string value). This happens every time the Form is opened with any of these data sources. However, Bookmarks are valid only during the current Form session — they are not stored permanently in Tables.

You can read the Bookmark of any record from the Form’s Bookmark property when that record is current, and store it in memory variables. These saved Bookmarks can then be used to quickly return to any record you previously visited.

To make this process easy to use, I’ve created a function called myBookMarks(). With just a Combo Box, a Command Button, and four lines of VBA code in the Form’s code module, you can implement this powerful navigation method on any Form that has an attached Recordset.

You’re sure to earn a pat on the back from your MS Access application’s users for adding this simple yet powerful feature. Let’s get started with our sample project.

SAMPLE PROJECT.

  1. Open your VBA Editing Window (Alt+F11).

  2. Create a new Standard Module (Insert -> Module), copy and paste the following Code of myBookMarks() Function into the Module, and Save it:

    Option Compare Database
    Option Explicit
    
    Public Const ArrayRange As Integer = 25
    Dim bookmarklist(1 To ArrayRange) As String, ArrayIndex As Integer
    
    Public Function myBookMarks(ByVal ActionCode As Integer, ByVal cboBoxName As String, Optional ByVal RecordKeyValue) As String
    '-----------------------------------------------------------------
    'Author : a.p.r. pillai
    'Date   : October-2009
    'URL    : www.msaccesstips.com
    'Remarks: All Rights Reserved by www.msaccesstips.com
    '-----------------------------------------------------------------
    'Action Code : 1 - Save Bookmark in Memory
    '            : 2 - Retrieve Bookmark and make the record current
    '            : 3 - Initialize Bookmark List and ComboBox contents
    '-----------------------------------------------------------------
    Dim ctrlCombo As ComboBox, actvForm As Form, bkmk As String
    Dim j As Integer, msg As String, bkmkchk As Variant
    Dim strRowSource As String, strRStmp As String, matchflag As Integer
    Dim msgButton As Integer
    
    On Error GoTo myBookMarks_Err
    
    If ActionCode < 1 Or ActionCode > 3 Then
       msg = "Invalid Action Code : " & ActionCode & vbCr & vbCr
       msg = msg & "Valid Values : 1,2 or 3"
       MsgBox msg, , "myBookMarks()"
       Exit Function
    End If
    
    Set actvForm = Screen.ActiveForm
    Set ctrlCombo = actvForm.Controls(cboBoxName)
    Select Case ActionCode
        Case 1
            bkmk = actvForm.Bookmark
            'check for existence of same bookmark in Array
            matchflag = -1
            For j = 1 To ArrayIndex
               matchflag = StrComp(bkmk, bookmarklist(j), vbBinaryCompare)
               If matchflag = 0 Then
                   Exit For
               End If
            Next
            If matchflag = 0 Then
               msg = "Bookmark of " & RecordKeyValue & vbCr & vbCr
               msg = msg & "Already Exists. "
               MsgBox msg, , "myBookMarks()"
               Exit Function
            End If
            'Save Bookmark in Array
            ArrayIndex = ArrayIndex + 1
            If ArrayIndex > ArrayRange Then
              ArrayIndex = ArrayRange
              MsgBox "Boookmark List Full. ", , "myBookMarks()"
              Exit Function
            End If
            bookmarklist(ArrayIndex) = bkmk
    
            GoSub FormatCombo
    
            ctrlCombo.RowSource = strRowSource
            ctrlCombo.Requery
        Case 2
            'Retrieve saved Bookmark and make the record current
            j = ctrlCombo.Value
            actvForm.Bookmark = bookmarklist(j)
        Case 3
            'Erase all Bookmarks from Array and
            'Delete the Combobox contents
            msg = "Erase Current Bookmark List...? "
            msgButton = vbYesNo + vbDefaultButton2 + vbQuestion
            If MsgBox(msg, msgButton, "myBookMarks()") = vbNo Then
                Exit Function
            End If
            For j = 1 To ArrayRange
               bookmarklist(j) = ""
            Next
            ctrlCombo.Value = Null
            ctrlCombo.RowSource = ""
            ArrayIndex = 0
    End Select
    
    myBookMarks_Exit:
    Exit Function
    
    FormatCombo:
    'format current Bookmark serial number
    'and OrderID to display in Combo Box
    strRStmp = Chr$(34) & Format(ArrayIndex, "00") & Chr$(34) & ";"
    strRStmp = strRStmp & Chr$(34) & RecordKeyValue & Chr$(34)
    
    'get current combobox contents
    strRowSource = ctrlCombo.RowSource
    
    'Add the current Bookmark serial number
    'and OrderID to the List in Combo Box
    If Len(strRowSource) = 0 Then
         strRowSource = strRStmp
    Else
         strRowSource = strRowSource & ";" & strRStmp
    End If
    Return
    
    myBookMarks_Err:
    MsgBox Err.Description, , "myBookMarks()"
    Resume myBookMarks_Exit
    End Function
  3. Import the following Tables from C:\Program Files\Microsoft Office\Office11\Samples\Northwind.mdb sample Database:

    • Order Details
    • Products

    Note: We are not using the second table directly; the Order Details table references the Products table to display the product descriptions.

    Demo Form Design

    • Click on the Order Details table to select it.

    • From the Insert menu, choose Form, then select AutoForm: Tabular from the list.

    • MS Access will automatically create a tabular form.

    • Save the form with the name Order Details.

    A sample image of a Tabular Form in Design View is given below.

  4. Adding a Combo Box and Command Button.

    1. Open the Order Details form in Design View.

    2. Expand the Form Header area and move the field headings down slightly to make room for a Combo Box and a Command Button, as shown in the sample design above.

    3. If the Toolbox is not visible, open it by selecting View → Toolbox.

    4. If the Control Wizards button on the Toolbox is currently selected, click it again to turn it off.

    5. Select the Combo Box tool from the Toolbox, then draw a Combo Box in the Header section of the form, following the layout shown earlier.

    6. With the Combo Box still selected, open its Property Sheet by choosing View → Properties.

  5. Change the following Property Values as shown below:

    • Name = cboBMList
    • Row Source Type = Value List
    • Column Count = 2
    • Column Widths = .5";1"
    • Bound Column = 1
    • List Rows = 8
    • List Width = 1.5"
  6. Change the Caption of the Child Label, attached to the Combo Box, to Bookmark List.

  7. Create a Command Button on the right side of the Combo Box.

  8. Display the Property Sheet of the Command Button.

  9. Change the following Property Values as shown below:

    • Name = cmdReset
    • Caption = << Reset.

    Form Class Module VBA Code.

  10. Display the Code Module of the Form (View -> Code).

  11. Copy and Paste the following VBA Code into the Module; Save and Close the Form:

    Option Compare Database
    
    Private Sub Form_DblClick(Cancel As Integer)
        'Save Current Record's Bookmark in memory
        myBookMarks 1, "cboBMList", Me![OrderID]
    End Sub
    
    Private Sub cboBMList_Click()
        'Retrieve the bookmark using the
        'index number from the Combobox List
        'and make the respective record current
        myBookMarks 2, "cboBMList"
    End Sub
    
    Private Sub cmdReset_Click()
        'Initialize Bookmarks and Combobox contents
        myBookMarks 3, "cboBMList"
    End Sub
    
    Private Sub Form_Unload(Cancel As Integer)    
    'Remove all Bookmarks from Memory
        myBookMarks 3, "cboBMList"
    End Sub

    Perform a Trial Run.

  12. Open the Order Details Form in Normal View.

  13. Double-click on one of the record selectors on the left side of the Form.

  14. Click on the ComboBox Drop-down control to check whether the OrderID value of the Record that you have double-clicked is added to the ComboBox List with a sequence number in the first column or not.

  15. Make a few more double-clicks on different Record selectors up or down in the form you like.

  16. Inspect the Combo Box entries once again to ensure that all record references have been added correctly, each with a running serial number.

    Now, let’s test whether we can quickly navigate back to any of these previously visited records by selecting their reference from the saved Bookmarks List displayed in the Combo Box.

  17. Click on the drop-down control of the Combo Box to display the list of Bookmarks and click on one of the items from the list.

    The record corresponding to the selected Order ID will become the current record on the Form. Even if multiple records share the same OrderID, this method will correctly navigate to the exact record you visited earlier because it uses the Bookmark, not a search based solely on the OrderID value. If you relied only on the OrderID, the Form would stop at the first matching record instead of the specific one you previously accessed.

    Try it out by selecting other items from the Combo Box list. This method can also be implemented on Forms using a Columnar layout.


    Important Points to Note.

    I would like to remind you that the list of Bookmarks is saved in the BookMarkList array within the myBookMarks() function in the Standard Module. The items in the ComboBox are populated from this array. We have dimensioned the array to hold 25 elements, though not all elements may be filled. The index number of each filled Bookmark in the array is stored in the first column of the ComboBox.

    Check the following declarations of the Function in the Global area of the Module:

    Public Const ArrayRange As Integer = 25
    Dim bookmarklist(1 To ArrayRange) As String, ArrayIndex As Integer

    You can adjust the value 25 to a higher or lower number according to your specific needs. Alternatively, you can redimension the BookMarkList() array dynamically using the ReDim Preserve statement to increase its size while keeping the existing values intact.

    Let us continue by adding a few more distant record bookmarks to the existing list.

  18. Scroll down the vertical scrollbar of the Form and double-click on the Record-Selectors for a few more records from the distant area of the Recordset.

  19. Now, try to reach any of these Bookmarks we have added to the list by selecting them one by one from the Combo Box List.

    Isn't it very easy to revisit all those records a second time?

  20. If you want to erase all those Bookmarks from the BookmarkList Array in memory, click on the << Reset Command Button. After this, you can create a fresh list of Bookmarks.

The OrderID Field Value added to the Combo Box, along with the Index Number of the Bookmark Array, can be used to cross-check with the retrieved record value to ensure correctness.

Review of VBA Code.

Let us review the Sub-Routines we have copied into the Form Module and check what they are doing.

Private Sub Form_DblClick(Cancel As Integer)

    myBookMarks 1, "cboBMList", Me![OrderID]

End Sub

When you double-click the Record Selector of a record, the above Sub-Routine calls the main function myBookMarks() with the following parameters:

  1. Action Code: 1 – indicates that the current Bookmark (a two-byte string containing displayable and non-displayable characters) should be fetched from the active Form and saved in memory in the BookMarkList array. The array index is incremented using the variable ArrayIndex. This Action Code is evaluated in the Select Case ... End Select block of the myBookMarks() function. Note that the Bookmark value itself is not displayed anywhere.

  2. Combo Box Name: "cboBMList" – This combo Box displays the index number of the BookMarkList array. Providing the control’s name is sufficient to reference it on the active Form.

  3. Record Field Value: OrderID – displays the record field value in the Combo Box alongside the BookmarkList array index. You can use any field from your table, as long as it helps verify that the correct record is retrieved using the Bookmark.

The third parameter of the myBookMarks() function is optional and is omitted when calling the function to retrieve a Bookmark or to clear the Bookmark list, as shown in the following three SubRoutines.

Private Sub cboBMList_Click()
myBookMarks 2, "cboBMList"

End Sub

Private Sub cmdReset_Click()
  myBookMarks 3, "cboBMList"

End Sub

' Erases the Bookmarks when the Form is closed

Private Sub Form_Unload(Cancel As Integer)

  'Remove all Bookmarks from Memory

  myBookMarks 3, "cboBMList"

  End Sub

NB: Since the main Function myBookMarks() references the Active Form, you can implement this method on any Form without directly passing any Form Name to the Function.

  1. Saving, retrieving, and using Bookmarks for finding records is valid only for the current Form session.

  2. Re-querying the Form's contents (not Refreshing) recreates the Bookmarks for the Recordset on the form, and saved Bookmarks may not be valid after that. You must create a fresh Bookmark List to use correctly.

  3. This method will not work on Forms attached to external Data Sources, linked to Microsoft Access, which doesn't support bookmarks.

Share:

PRESENTATION: ACCESS USER GROUPS (EUROPE)

Translate

PageRank

Post Feed


Search

Popular Posts

Blog Archive

Powered by Blogger.

Labels

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