Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Web Browsing within Access Form

Introduction

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 right-bottom-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 with the name myWebBrowser.

    Demo Run of the Form

  12. Connect your PC to the Internet.

  13. Open myWebBrowser Form in normal View.

  14. Wait for a few seconds to load the Web Page into 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 the copy as 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 the 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 clicking on the Links from the displayed page, then we can navigate (go Back or Forward) 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 global declaration section of the module.

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, which 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 on the Header of the Form, as shown to the right of the Combo box Control on the above design, and write Subroutines with some simple Browser Object Commands to navigate between Web Pages, which we may open from the displayed Web Pages.

Web Navigation Controls

  1. Open 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 the Subroutines from running into an 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:

Text Search Filter Web Style

Introduction

How to search for several pieces of information across all the fields and in all the records of a Table?

For example, when we search for something on the web, we often enter multiple keywords separated by the Space character or the “+” symbol. The search engine then looks for any of the specified terms across web pages and displays the matching results on the screen.

Search text example 1: ms-access, forms, reports, queries

Or

Search text example 2: ms-access+forms+reports+queries

In the same way, we can create filters to display records from a table that match several pieces of Text/numbers/Phrases across any field in any record.

Last week, we learned how to use the BuildCriteria() function to filter data using a single field. The BuildCriteria() function accepts only one field as its first parameter. In this session, we’ll use the same function again — but with a clever trick that allows us to apply it to all the fields in a table.

A Simple Demo Run

So let us do this with a simple Query and a Tabular Form.

  1. Import Customers Table from:

    C:\Program Files\Microsoft Offce\Office11\Samples\Northwind.mdb sample database.

  2. Create a new Query based on the Customers table, including all its fields.
    Then, add a calculated column named FilterField to the Query.

  3. Write the following expression in the new column to join all the Text and Numeric Field values together into a single Column:

    FilterField: [CustomerID] & " " & [CompanyName] & " " & [ContactName], etc., join all the fields this way except HyperLinks, Objects, and Yes/No Field Types. Save the Query with the name myQuery.

    You can automate this task using the following VBA program.
    Before running the code, create a Query manually that includes at least one field from the source table and name it myQuery.

    If you prefer to use a different Query name, simply modify the program wherever the reference to "myQuery" appears to match your chosen name.

    The CombineData() Code.

    Public Function CombineData(ByVal tblName As String)
    '----------------------------------------------------------
    'Author : a.p.r. pillai
    'Date   : December 2009
    'Rights : All Rights Reserved by www.msaccesstips.com
    '----------------------------------------------------------
    Dim strsql1 As String, db As Database, qrydef As QueryDef
    Dim fldName As String, k As Integer, j As Integer
    Dim tbldef As TableDef, strjoin As String
    
    On Error Resume Next
    
    strsql1 = "SELECT " & tblName & ".*, "
    Set db = CurrentDb
    Set qrydef = db.QueryDefs("myQuery")
    
    Set tbldef = db.TableDefs(tblName)
    k = tbldef.Fields.Count - 1
    
    strjoin = ""
    For j = 0 To k
        If tbldef.Fields(j).Type <> 1 And tbldef.Fields(j).Type <> 11 And tbldef.Fields(j).Type <> 12 Then
            If Len(strjoin) = 0 Then
                strjoin = "[" & tbldef.Fields(j).Name & "] "
            Else
                strjoin = strjoin & " & " & Chr$(34) & " " & Chr$(34) & " &  [" & tbldef.Fields(j).Name & "] "
            End If
        End If
    Next
    
    strsql1 = strsql1 & "(" & strjoin & ") AS FilterField FROM " & tblName & ";"
    qrydef.SQL = strsql1
    db.QueryDefs.Refresh
    
    Set tbldef = Nothing
    Set qrydef = Nothing
    Set db = Nothing
    
    End Function
    • Copy and paste the above VBA Code into a Standard Module and save it.

    •  Display the VBA Debug Window (Ctrl+G).

       Run the Program from the Debug Window by typing the following statement and pressing the Enter Key:

    CombineData "Customers"

    This program modifies the design of myQuery by combining all fields from the Customers table (or any other source table you specify), except for fields of the following types:

    • Hyperlink

    • Object (OLE Object)

    • Yes/No

    • Memo (Long Text)

    A new calculated column named FilterField will be created, which concatenates the values of all supported fields.

    If you also need to include Memo field contents, you must add that field manually in the Query Design view.
    The CombineData() Function intentionally skips Hyperlink, Object, and Memo fields because they all share the same internal data type category, and the program’s validation logic excludes them by design.

    The Sample Datasheet view image of the FilterField in myQuery is given below:


    Design a Form

  4. Create a Tabular Form (continuous form) using myQuery as Record Source and save the Form with the name frmMyQuery.

  5. Open the form frmMyQuery in the Design view.

  6. Select the FilterField Column and display its Property Sheet (View ->Properties)

  7. Change the Visible Property Value to No.

  8. Make the FilterField column size very small on the Form (it is not visible on normal view) and resize other Columns to view their contents properly.

  9. Remove columns such as Region, Fax, or any other fields that you consider unnecessary for this test run.
    This will help ensure that all the required columns fit neatly on a single screen for easier viewing and testing.

  10. Expand the Form Header Section and drag the column headings down so that we will get enough space to draw a TextBox and a Command Button beside it.

  11. Create a Text Box above the column headings.

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

  13. Change the following Property Values as given below:

    • Name = txtSearch
    • Width = 3"
  14. Change the Caption of the Child Label of the Text Box to Search Text (delimiter:, or +):

  15. Create a Command Button to the right of the Text Box and change the following Property Values:

    • Name = cmdGo
    • Caption = GO>

    The Form's Class Module Code.

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

  17. Copy and Paste the following VBA Code into the Module.

    Private Sub cmdGo_Click()
    '----------------------------------------------------------
    'Author : a.p.r. pillai
    'Date   : December 2009
    'Rights : All Rights Reserved by www.msaccesstips.com
    '----------------------------------------------------------
    Dim x_Filter, j As Integer
    Dim Y_Filter, Xchar As String, flag
    
    x_Filter = Nz(Me![txtSearch], "")
    
    If Len(x_Filter) = 0 Then
        Me.FilterOn = False
        Exit Sub
    End If
    'Code segment that tests and removes extra spaces'
    'between coma and next search text item.
    
    '--Extra space removal Segment start-
    Y_Filter = ""
    For j = 1 To Len(x_Filter)
        Xchar = Mid(x_Filter, j, 1)
    ' Test for presence of , or + and leading spaces
        If (Xchar = "," Or Xchar = "+") And Mid(x_Filter, j + 1, 1) = " " Then
                flag = True
        ElseIf Xchar = " " And flag Then
                flag = False
                Y_Filter = Trim(Y_Filter)
        End If
        Y_Filter = Y_Filter & Xchar
    Next
    x_Filter = Y_Filter
    
    '--Extra space removal Segment End-
    
    Y_Filter = "*"
    For j = 1 To Len(x_Filter)
            Xchar = Mid(x_Filter, j, 1)
         'Validation check
          If Xchar = "(" Or Xchar = ")" Then
                    MsgBox "Invalid Characters () in expression, aborted... "
                    Exit Sub
         End If
    If Xchar = "," Or Xchar = "+" Then
    'test for presence of ,+
         Xchar = "* OR *"
    End If
    Y_Filter = Y_Filter & Xchar
    Next
    
    Y_Filter = Y_Filter & "*"
    Me.FilterOn = False
    Y_Filter = BuildCriteria("FilterField", dbText, Y_Filter)
    Me.Filter = Y_Filter
    Me.FilterOn = True
    
    End Sub 

    The Sample Demo Run.

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

  19. Type some Text/Numbers/Phrases separated with commas (,) or plus symbol (+), which can match in any part of any Field(s) or in different Record(s), in the Text Box.

    Example 1: FRANK, Elizabeth Brown, Brazil

    Example 2: FRANK+Elizabeth Brown+Brazil

    Example 3: Frank Elizabeth Brown, Brazil

    Note: Do not use parentheses ( ) in the search text, as they can cause errors when processed by the BuildCriteria() function. Users might accidentally include extra spaces between the text separator (such as the + symbol) and the next search item; these extra spaces are automatically removed by the program before the search and filter operations begin.

  20. However, spaces within phrases (embedded spaces) in the search text will remain intact.

  21. Click on the GO> Command Button to search for the given text in fields/records and filter those records on the Form.

  22. You may inspect the filtered records to ensure that one or more of the search texts you have entered into the Text Control appear in all the filtered records. They can appear in any field or fields in any Record, but all the records filtered will have these texts/numbers/phrases on them.

Share:

Filter with BuildCriteria Function

Introduction

Any method that helps users find data quickly on a form is always appreciated. In Form View mode, several options are available to locate records efficiently.

When you right-click on a field, a shortcut menu appears, displaying four data filter options, as shown in the sample image below.

The third option, Filter For, accepts a criteria expression such as

>10200 AND <=10300
to filter a specific range of values from the selected field.

If you’d like to explore more filtering options, point to the Filter option on the Records menu. There, you’ll find two additional choices: Filter by Form and Advanced Filter/Sort.

Filter by Form allows you to set up criteria in multiple fields to select records based on values entered directly into form fields.

Advanced Filter/Sort opens the Filter Design (or Query Design) window, displaying the source table or query of the form, along with any criteria you may have already entered using Filter For or Filter by Form. You can then further modify your filter conditions, adjust the sorting order, and select Apply Filter from the Records menu to view the results.

However, if you’d like to build a custom filter option for the user—based on a specific field on the form—you can use the built-in BuildCriteria() function. By writing a VBA subroutine around this function and running it from a command button’s Click event, you can allow the user to input filter criteria in flexible ways.

The function usage is quite simple. Let’s try a few examples directly in the Immediate (Debug) Window to see how it works.

  1. Press Alt+F11 to display the Visual Basic Editing Window.

  2. Press Ctrl+G to display the Debug window.

  3. Type the following example expressions and press the Enter key to display the output:

Sample Run of BuildCriteria() Function

? BuildCriteria("OrderID",dblong, "10200")

Result: OrderID=10200

 The BuildCriteria() function requires three parameters.

In the example, OrderID is the data field name, dbLong indicates that OrderID is a numeric field of type Long Integer, and the last value 10200 represents the criteria value used to select matching records.

The BuildCriteria() function automatically inserts the field name (OrderID) into the correct positions within the criteria expression.

The third parameter can be used in different ways depending on the result you want to achieve. Let’s explore a few more examples to better understand its flexibility before we implement this method on a form.

Type the following expressions in the Immediate (Debug) Window to see how the function behaves:

? BuildCriteria("OrderID",dblong, ">=10200 AND <10300")

Result: OrderID>=10200 And OrderID<10300

 ? BuildCriteria("OrderID",dblong,">=10200 AND <10300 OR >=10400 AND <10500")

Result: OrderID>=10200 And OrderID<10300 Or OrderID>=10400 And OrderID<10500

Try changing the data type to dbText, for example:

? BuildCriteria("OrderID",dbText, "10200")

Result: OrderID="10200"

? BbuildCriteria("OrderDate",dbDate,">10/15/2009 and <=10/31/2009")

Result: OrderDate>#10/15/2009# And OrderDate<=#10/31/2009#

Using on Form to Filter Data

After getting the result text from the BuildCriteria() Function, all we have to do is insert it into the Filter Property of the Form and turn ON the Filter action.

Let us design a simple Form to run our example straight away.

  1. Import the Orders

    Table from C:\Program Files\Microsoft Office\Officell\Samples\Northwind.mdb sample database.

  2. Select the Orders Table and select Form from the Insert Menu.

  3. Select Auto Form: Tabular to create a Form and save it with the name Orders.

  4. Open the Orders Form in Design View.

  5. Expand the Form Header Area and drag all the Field Headings down to get enough room to create a Command Button above the Field Headings.

  6. Display the Toolbox, if it is not visible (View ->Toolbox).

  7. Select the Command Button Tool and create a Command Button on the Header of the Form.

  8. While the Command Button is still in the selected state, display its Property Sheet (View -> Properties).

  9. Change the Name Property Value to cmdFilter and change the Caption Property Value to OrderID Filter.

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

    Run it with a Button Click

  11. Copy and Paste the following VBA Code into the Module.

    Private Sub cmdFilter_Click()
    Dim txtCondition, txtFilter As String
    
    txtCondition = InputBox("OrderID Value/Range of Values")
    If Len(txtCondition) = 0 Then
        Me.FilterOn = False
        Exit Sub
    End If
    
    txtFilter = BuildCriteria("OrderID", dbLong, txtCondition)
    
    Me.FilterOn = False
    Me.Filter = txtFilter
    Me.FilterOn = True
    
    End Sub
  12. Save and Close the Form.

  13. You may click on the OrderID Filter Command Button and enter any of the examples (except the one with Date) criteria expressions we have entered as the third Parameter into the BuildCriteria() Function above, when prompted for the Filter Condition.

Setting up Criteria Value on Text Box.

If you don't like to use InputBox() to prompt for Criteria Values, then you may create a Text Box on the Form where Users can enter the Criteria expression before hitting the Command Button.

The limitation of the BuildCriteria() Function is that it can accept only one field as the first parameter. But there is a way to use more than one field in the Filter condition on the Form. Ask the User to enter conditions for two different fields separately, and run the BuildCriteria() Function also separately to obtain the results. Join both results with AND/OR Logical operators to filter the data.

The following example code uses OrderID and ShipName field values to filter data on the Orders Form.

  • Create a Copy of the Orders Form and name the Form Orders2.

  • Open the Form in Design View.

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

  • Copy and paste the following Code into the Module, replacing the existing Code:

Private Sub cmdFilter_Click()
Dim txtOrderNumber, txtOrderfilter As String
Dim txtShipName, txtShipNameFilter As String
Dim msg As String, resp, txtFilter As String

txtOrderNumber = InputBox("OrderID Value/Range of Values to Filter")
txtShipName = InputBox("ShipName/Partial Text to Match")

If Len(txtOrderNumber) > 0 Then
    txtOrderfilter = BuildCriteria("OrderID", dbLong, txtOrderNumber)
End If

If Len(txtShipName) > 0 Then
    txtShipNameFilter = BuildCriteria("ShipName", dbText, txtShipName)
End If

If Len(txtOrderfilter) > 0 And Len(txtShipNameFilter) > 0 Then
    msg = "1. Filter items-that matches both filter conditions" & vbCr & vbCr
    msg = msg & "2. Matches either one or Both conditions" & vbCr & vbCr
    msg = msg & "3. Cancel"
    Do While resp <> 1 And resp <> 2 And resp <> 3
        resp = InputBox(msg)
    Loop
    Select Case resp
        Case 3 
           Exit Sub
        Case 1
            txtFilter = txtOrderfilter & " AND " & txtShipNameFilter
        Case 2
            txtFilter = txtOrderfilter & " OR " & txtShipNameFilter
    End Select
Else
    txtFilter = txtOrderfilter & txtShipNameFilter
    If Len(Trim(txtFilter)) = 0 Then
       Exit Sub
    End If
End If

Me.FilterOn = False
If Len(Trim(txtFilter)) > 0 Then
    Me.Filter = txtFilter
    Me.FilterOn = True
End If

End Sub

How does it work?

The first two InputBox() Functions collect the Filter Criteria for OrderID and ShipName Field values separately. Next steps: Validate the User responses and build the criteria strings in the txtOrderFilter and txtShipNameFilter Variables.

If both Variables have filter conditions in them, then the User response is collected to check whether the user needs the result set that meets both conditions (AND) or the result set that meets any one of the conditions or both (OR).

The Filter Strings are joined accordingly to obtain the intended result. The User doesn't need to always provide both sets of Criteria Values (for Orderld and ShipName) all the time. They can use only one Field for entering Criteria and ignore the other.

Share:

Save User Specific Parameter values

Introduction

Last week, we created a Report Parameter Control Form for concurrent users on a network, ensuring that each user’s report filter parameters do not conflict with others while generating different versions of the same report.

To achieve this, we avoided using a parameter table as the record source for the parameter form. Instead, we added two unbound text boxes for entering the parameter values, which are then used to set the filter conditions in the report’s source query.

Additionally, we saw how to save these parameter values in the form’s Custom Properties when the form is closed, preserving them for future use.

The sample image of the Report Parameter Form: RptParameter is given below for reference:

Last week, we used the parameter control text boxes FromDate and ToDate to enter date-range values as criteria for filtering data in the report’s source query. The custom property names we created were slightly modified versions of these text box names, such as DateFrom and DateTo.

One question we raised was: Is it possible to save and retrieve the report parameter values entered by each user in different instances of the same form without overwriting someone else’s values?

In last week’s example, there was only one set of custom properties created for all users and all instances of the form. Consequently, the last user on the network who closes their form instance will overwrite the custom property values of earlier users. These overwritten values will then be loaded back into the text boxes the next time the form is opened.

User-based Custom Property Name Format.

The solution is straightforward: create custom properties on the form for each user and save the values entered by that user when their instance of the parameter form is closed.

To uniquely identify each user’s values, combine the user name with the text box name when naming the custom property. This ensures that each user has a distinct custom property, preventing one user’s input from overwriting another’s.

For example:

  • User-Name: JSmith
  • Parameter TextBox Name1: fromDate
  • Parameter TextBox Name2: toDate
  • Custom Property Name1: JSmithDateFrom
  • Custom Property Name2: JSmithDateTo

 We can retrieve the user name of the current form instance using the CurrentUser() function.

When the User-Name prefixes the Custom Property Names, we can easily save and retrieve individual users' parameter values and use them on their instance of the same Form as well.

Another point to remember is that new users may be added to the same Workgroup, and this method should work for them also when they start using the RptParameter Form.

We must write the VBA Routines in such a way that whenever a new user starts working with the RptParameter Form, the User must be identified as a newcomer and the Custom Properties for that User must be created automatically.

The Custom Property Creation Code.

  1. The modified Custom Properties creation Program is given below. Copy and paste the code into a Standard Module of your Database.
    Public Function CreateCustom_Property(ByVal frmName As String, ByVal usrName As String)
    '-------------------------------------------------------------------------
    ' Author : a.p.r. pillai
    ' Date   : November-2009
    ' All Rights Reserved by www.msaccesstips.com
    '-------------------------------------------------------------------------
    Dim cdb As Database, doc As Document
    Dim prp As Property, getPrpValue
    Dim fld1 As String, fld2 As String
    
    On Error Resume Next
    
    fld1 = usrName & "DateFrom"
    fld2 = usrName & "DateTo"
    
    Set cdb = CurrentDb
    Set doc = cdb.Containers("Forms").Documents(frmName)
    
    'check whether the Property of the current user exists
    getPrpValue = doc.Properties(fld1).Value
    
    If Err = 3270 Then 
    ' referenced Property doesn't exist
        Err.Clear
    'create Property for new User
        Set prp = doc.CreateProperty(fld1, dbDate, Date)
        doc.Properties.Append prp
        Set prp = doc.CreateProperty(fld2, dbDate, Date)
        doc.Properties.Append prp
        doc.Properties.Refresh
    End If
    
    Set prp = Nothing
    Set doc = Nothing
    Set cdb = Nothing
    
    End Function
  2. Create a Copy of the RptParameter Form with the name RptParameter2.
  3. Open the RptParameter2 Form in Design View.
  4. Display the VBA Module of the Form (View -> Code).

    Revised VBA Code - Form Load.

  5. Copy and paste the following Sub-Routines into the VBA Module, overwriting the earlier Code:
    Private Sub Form_Load()
    Dim cdb As Database, doc As Document
    Dim fld1 As String, fld2 As String
    
    fld1 = CurrentUser & "DateFrom"
    fld2 = CurrentUser & "DateTo"
    
    'Validate Current User's Status
    'If, necessary create Custom Properties for new User
    CreateCustom_Property Me.Name, CurrentUser
    
    DoCmd.Restore
    
    Set cdb = CurrentDb
    Set doc = cdb.Containers("Forms").Documents(Me.Name)
    Me![fromDate] = doc.Properties(fld1).Value
    Me![toDate] = doc.Properties(fld2).Value
    
    Set cdb = Nothing
    Set doc = Nothing
    
    End Sub
    

    Revised VBA Code - Form Close.

    Private Sub Form_Close()
    Dim cdb As Database, doc As Document
    Dim fld1 As String, fld2 As String
    
    fld1 = CurrentUser & "DateFrom"
    fld2 = CurrentUser & "DateTo"
    
    Set cdb = CurrentDb
    Set doc = cdb.Containers("Forms").Documents(Me.Name)
    
    doc.Properties(fld1).Value = Me![fromDate]
    doc.Properties(fld2).Value = Me![toDate]
    
    Set cdb = Nothing
    Set doc = Nothing
    End Sub
  6. Save and Close the Form.

Review of Programs.

As shown in the Form_Load() event procedure, the custom property creation routine CreateCustom_Property() is called only when a user (new or existing) opens the RptParameter2 form.

This means that custom properties are not created for all users in the database—they are only created for users who interact with this specific form.

The Report Parameter Form should be tested simultaneously from different machines by multiple users. Each user can enter their own values in the parameter control text boxes (FromDate and ToDate) to test the procedure. When the same users open the form in a later session, the values they entered previously should automatically appear in the respective text boxes.

Note: The above procedure has not been extensively tested for bugs or side effects, so it should be used at your own risk. If you encounter any issues, please share them. The procedure assumes that the database is implemented with Microsoft Access Security.

For unsecured databases, visit the page Unsecured Database and Users Log to learn how to retrieve a user’s name. In unsecured databases.  The CurrentUser() function will always return the username as Admin.

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