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

VBA Module Object and Methods

Introduction.

The VBA Module Object has several interesting methods and properties.  Last week, we saw how to insert a Click Event Procedure in a Form Module with a Function. You can find this blog post here.

I don’t say that frm.Module.CreateEventProc()  The method, which we have tried, was an easy approach for writing a one-line statement in a Form Module.  But, trying something different is always exciting; programming is like exploring the unknown.  After all, it is there as part of the Application to explore and learn. 

Today, we will try an alternative and simple method for the same example we tried last week.  That is to write all the program lines in a text file and load that program directly into the Form Module.

If you have tried last week’s example, we can use the same ‘Sample’ Form for today’s trial run,  or do the following to get prepared:

Loading VBA Code from Text File.

  1. Open a new Form in Design View.

  2. Create a Command Button on the Detail Section of the Form.

  3. While the Command Button is in the selected state, display its Property Sheet (F4 or ALT+Enter).

  4. Change the Name Property Value to cmdRun and the Caption Property Value to Run Report.

  5. Save the Form with the name Sample.

  6. If you have last week’s Sample form, then open it in Design View.

  7. Display the Form Module, remove the existing program lines, and save the Form.

  8. Open Notepad, copy and paste the following program lines into Notepad, and save it as c:\windows\temp\vbaprg.txt

    Private Sub cmdRun_Click()
    
        DoCmd.OpenReport "myReport", acViewPreview
    
    End Sub
  9. Replace the report name "myReport" with one of your own Report Names from the database.

  10. Open a Standard VBA Module, copy and paste the following main program into the Standard Module:

    The LoadFromTextFile() Function.

    Public Function LoadFromTextFile()
    Dim frm As Form, frmName As String, ctrlName As String
    
    frmName = "Sample"
    'ctrlName = "cmdRun"
    
    'Open the form in design view
    DoCmd.OpenForm frmName, acDesign
    
    'define the form object
    Set frm = Forms(frmName)
    
    'call the form's Module Object's AddFromFile() method
    'to read the program from the text file
    'and insert them into the Form Module
    frm.Module.AddFromFile "c:\windows\temp\vbaprg.txt"
    
    'Save and close the form with the code
    DoCmd.Close acForm, frmName, acSaveYes
    
    'Open the form in Normal view
    DoCmd.OpenForm frmName, acNormal
    
    End Function
  11. Place the cursor in the middle of the Code and press F5 to run the Code.

  12. Press ALT+F11 to display the Database window with the Sample Form open.

  13. Click on the Command Button to open the Report in print preview.

  14. Close the Report.

  15. Change the Sample Form in Design View.

  16. Open the form module and check for the program lines we have loaded from the vbaprg.txt file.
Technorati Tags:

Earlier Post Link References:

Share:

Writing VBA-Code with VBA

Introduction.

To insert an Event Procedure in a Form or Report, we will open the VBA Module and write the code manually.  If we open the Class Module through the Event Property on the Property Sheet of a Control or Form (after setting the “[Event Procedure]” value in the Event property), then the procedure’s opening and closing statements (see the example given below) will be inserted by Microsoft Access automatically. After that, we insert the necessary body lines of the procedure manually between those opening and closing statements.

Sample empty Subroutine stub of Form_Current() Event Procedure is shown below:

Private Sub Form_Current()

End Sub

Let us do it differently this time by programming a Command Button Click event procedure automatically through VBA. We are going to insert a Command Button Click Event Procedure in a Form Module with the help of a Function Write_Code().  We learned something similar through an earlier article on the topic: Creating an Animated Command Button with VBA

A sample Trial Run.

In this trick, the Command Button is programmed automatically to open a Report in Print Preview.  The following are the lines of VBA Code we are going to insert into the Form Module automatically:

Private Sub cmdRun_Click()

    DoCmd.OpenReport "myReport", acViewPreview

End Sub
  1. Open a new blank Form in Design View.

  2. Add a Command Button control on the Form.

  3. While the Command button is in the selected state, display its Property Sheet (F4 or ALT+Enter).

  4. Change the Name Property Value to cmdRun.

  5. Change the Caption Property Value to Run Report.

  6. Save and close the Form with the name frmSample.

  7. Open VBA Editing Window (ALT+F11) and insert a new Standard Module. You can toggle Database and Code Window with the ALT+F11 Keyboard shortcut.

  8. Copy and paste the following Code into the Standard Module and save it:

    Public Function Write_Code(ByVal frmName As String, ByVal CtrlName As String)
    Dim frm As Form, x, txt As String, ctrl As Control
    
    DoCmd.OpenForm frmName, acDesign, , , , acHidden
    Set frm = Forms(frmName)
    Set ctrl = frm.Controls(CtrlName)
    With ctrl
        If .OnClick = "" Then
           .OnClick = "[Event Procedure]"
        End If
    End With
    
    x = frm.Module.CreateEventProc("Click", ctrl.Name)
    
    txt = "DoCmd.OpenReport " & Chr$(34) & "myReport" & Chr$(34) & ", acViewPreview"
    frm.Module.InsertLines x + 1, txt
    
    DoCmd.Close acForm, frmName, acSaveYes
    DoCmd.OpenForm frmName, acNormal
    
    End Function
  9. Replace the Report name "myReport" with one of your own Report names in the program line: txt = "DoCmd.OpenReport " & Chr$(34) & "myReport" & Chr$(34) & ", acViewPreview".

  10. Display the Debug Window (Ctrl+G).

  11. Type the following line in the Debug Window and press Enter Key:

    Write_Code "frmSample","cmdRun"

    The Form’s name "frmSample"  is passed as the first parameter to the Write_Code() Function, and the Command Button’s name "cmdRun" is passed as the second parameter.

  12. Press ALT+F11 to display the Database window.  You can see that frmSample is already open in normal view after inserting the program lines in its Code Module.

  13. Click on the Command Button to open your Report in Print Preview with the cmdRun_Click() Event Procedure.  You may change the Form View into Design View, open the Form Module, and check the lines of Code we have inserted in there.

At the beginning of the above program, the OnClick Event Property is checked for the presence of any programmed action, like a Macro Name, and if found empty, then it inserts the text "[Event Procedure]" in the property in preparation for writing the program lines in the VBA Module.

In the next step, the Form Module’s CreateEventProc() method is called to create the Click Event Procedure of the Command Button: cmdRun.  If you want a Double-Click Event procedure, rather than a Click() event procedure, then change the word "Click" to "dblClick".

Replace the 'DoCmd.OpenReport' statement with appropriate Code for other actions like MouseMove.

You can call the Write_Code() function from a Command Button and click Event Procedure on a Form.  Create two TextBoxes on the Form, enter the Form Name and Control Names in them respectively, and use the text box names in both parameters of the Write_Code() function.

Earlier Post Link References:

Share:

Control SetFocus on Tab Page Click

Introduction

A question was raised in an MS Access Discussion Forum:

"When I click on a Tab Control Page, I want to set focus on a particular Text Box on that page, not on the first Text Box by default. How can I do this?"

The user attempted a solution by writing code in the Page2_Click() event procedure of the Tab Control. Specifically, they tried variations of the following lines to set focus on the "Ship City" text box located on that page:

Private Sub Page2_Click()
     Forms!frm_Main![Ship City].SetFocus 
     frm_MainMenu![Ship City].SetFocus 
     me.[Ship City].SetFocus 
End Sub 

Tab Control-based Menus.

The Tab Control is an interesting and versatile object to use on a form. Personally, I have often used it to build form-based menus, placing list boxes on its pages to organize navigation options. For example, the image below shows a sample control screen with list box–based menus arranged neatly on the tab pages.

The middle of the Control Form shows a list as a menu of choices.  In fact, there are fifteen different sets of menus displayed there.  They are displayed one over the other by clicking on a set of Command Buttons, shown on either side of the list box.  You can learn this trick here.

Use Change Event for Click Event.

Coming back to the topic, the first thing that you should know is that when you click on the Tab-Page Button (see the sample image below) on a Tab-Control, the Click Event procedure will not be fired; instead, it fires the Change() Event. So use the Change() Event for Tab Page Clicks.

The Click event of a Tab Control fires only when you click on the top border area to the right of the tab pages. This means you need two clicks: one to select the tab-page button (to display its contents), and another on the Tab Control’s border to trigger the event procedure. Clearly, this is not a convenient approach. Instead, we will take an alternative route that allows the task to be completed with a single click, using a different method.

If you have already explored the text links provided earlier, you may have picked up a few ideas—and are probably one step ahead of what I am about to explain here.

Single Click Solution.

The simple method is using the Change Event Procedure on the TabPage Click.

We will implement the following ideas for a different approach:

  1. Create a separate Command Button for each Tab-Page, with one line of VBA code to make it current or visible.

  2. In the Command Button Click Event Procedure, we will add one more line of code to move the focus to a particular text box in the middle of the tab page.

  3. Since we have Command Buttons to display Tab Pages, we will hide the Tab-Page Buttons of the Tab-control. Optionally, change the Tab-control’s back-style design to transparent to make the tab control’s border design invisible.

Skipping the Fancy Work.

Before diving into the detailed design of the steps mentioned earlier, let me share a very simple solution—if you’re not interested in all the extra work. Simply set the Tab Index property of the text box (for example, [Ship City]) to 0.

Be careful not to confuse the Tab Index with the Tab Control or Tab Page. The Tab Index property determines the order in which the cursor moves from one control (such as a text box, combo box, or check box) to the next when you press the Tab key on the keyboard.

These values are assigned sequentially, starting from 0 up to the number of controls that have a Tab Index property on the form. Access sets these values automatically, based on the order in which you add controls to the form—either manually or through the Form Wizard. When the form opens, the control with Tab Index = 0 receives the focus by default, regardless of where it is physically placed on the form.

So, if the [Ship City] Field is not the starting point on your form and you want to make it, then do the following:

  1. Open the form in design view.

  2. Click on the [Ship City] field to select it.

  3. Display its Property Sheet (F4 or ALT+Enter).

  4. Find the Tab Index Property and change the Value to 0.  Other controls’ Tab Index Property values will be automatically changed by Access.  You must review and change them, if needed, to bring them into the desired order.

NB:  Each Tab Page is like a separate sub-form and has a separate set of Tab Index sequence numbers starting with zero on it, even if you place a different group of fields from the current record.

Showing your Professionalism.

Now that you already know the quick and easy solution, let’s explore some advanced tricks for working with Tab Control programming.

Building a database to store and retrieve data is relatively simple—almost anyone can put one together using whatever method they find easiest. That might be fine for personal use, but when presenting a database to a client or end user, appearance and usability matter a great deal. A well-designed interface not only improves user experience but also reflects your professionalism and attention to detail.

Returning to our topic, let’s take a closer look at the first three steps of the alternative approach we outlined earlier. For this demonstration, we’ll design a sample form with a Tab Control containing three pages, each holding different groups of information from the Orders table in the Northwind sample database. You can use any table of your choice to create a similar form. On the left side of the Tab Control, add three command buttons to support our trial run.

The Design Task

  1. Click on the first Command Button to select it.

    • Display its Property Sheet (F4 or ALT+Enter keys).

    • Change the Name Property Value to cmdOrder and the Caption Property Value to Order Details.

    • Click on the Event Tab of the Property  Sheet, select On Click Event property, and select [Event Procedure] from the drop-down control.

    • Click on the Build ( . . . ) Button to open the Form’s VBA Module with an empty sub-routine stub.

    • Copy and paste the following lines of Code, overwriting the existing lines, or simply copy the middle line alone and paste it between the sub-routine opening and closing lines, as shown below.

      Private Sub cmdOrder_Click()
        Me.TabCtl0.Pages(0).SetFocus
      End Sub
  2. Similarly, change the middle Command Button’s Name Property Value to cmdShipper and Caption Property Value to Shipper Details.

    • Follow the last three steps mentioned above to copy-paste the following code for the middle Command Button Click Event Procedure:
      Private Sub cmdShipper_Click()
        Me.TabCtl0.Pages(1).SetFocus
        Me.Ship_City.SetFocus
      End Sub

      In the first line of code, we changed the Tab page reference from Page(0) to Page(1), which points to the second page of the Tab Control. We then added one more line:

      Me.Ship_City.SetFocus

      This moves the insertion point directly to the Ship City field, regardless of its physical placement on the form. As a result, a single click on the command button not only switches to the second tab page but also sets the focus on the Ship City field.

      Notice that we are addressing the control (Me.Ship_City.SetFocus) as though it were placed directly on the form surface, rather than treating it as a child control of the Tab Page. Keep in mind that each group of fields on a Tab Page has its own Tab Index sequence, starting from 0, which determines how the cursor moves among controls on that page.

      If you prefer, you can also reference the control explicitly as a child of the Tab Page, like this:

      Me.TabCtl0.Pages(1).Controls("Ship City").SetFocus

      This approach is equally valid.

  3. Change the last Command Button’s Name Property Value to cmdPayment and Caption Property Value Payment Details.

    • Copy-paste the following lines of code for the last Command Button Click Event Procedure, as you did in the earlier two cases:
      Private Sub cmdPayment_Click()
         Me.TabCtl0.Pages(2).SetFocus
      End Sub
  4. Save the Form and open it in the normal view. When you open the form, by default, Page1  of the tab control will be active.

  5. Click on the middle Command Button. You can see the second page of the Tab Control become active, and the control "Ship City" field is in focus now.

  6. Click on the Payment Details Command Button to select the third page. You may try all the command buttons repeatedly to get the feel of their usage.

    Since our command buttons took over the function of Tab-Pages of the Tab Control Object, we don't need the Tab Control Page buttons above, and we will remove them.

  7. Change the Form Mode in Design View.

  8. Click on the Tab Control by clicking on the right side of the Page3 button.

  9. Display the Property Sheet (F4).

  10. Click on the All tab of the property sheet and set the Style Property Value to None from the drop-down list.

The Demo Run.

If you open the form in Normal View, the Tab Control will appear as shown in the image below, without the tab page indicators. Clicking the command buttons will still switch the pages, just as before.

You can take this a step further by “hiding” the Tab Control’s identity marks entirely. To do this, set the

Back Style property of the Tab Control to Transparent. This creates a clean, seamless interface while retaining full tab functionality—a simple but impressive “magic trick.”

  1. Change the form to design view (if the form is in normal view) and change the Back Style Property Value to Transparent.

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

    No sign of the Tab Control now, except for displaying the controls on the first Tab Page with their values and labels. Click on the Command Buttons one after the other. You will find that the data fields and their labels appear from nowhere, occupying the same area every time, like magic.

Share:

Adding Data directly into External Databases

Introduction.

The Back-End/Front-End database design is a common practice in Microsoft Access. The back end may consist of Access, dBase, SQL Server, Excel, or Paradox databases, with their tables linked to the front end (FE). Once the tables are linked, they behave just like native tables within Access—you can design queries, forms, and reports on them, and manage everything from the FE.

But what if we want to work without directly linking these tables to the FE? For example, can we create a query in the current database that uses an external table (not linked) from another Access database?

We have already explored this topic earlier and confirmed that it is indeed possible. You can check the following blog posts for practical demonstrations of this technique applied to different types of external data sources:

  1. Opening External Data Sources
  2. Opening dBase Files directly
  3. Opening an Excel Database directly
  4. Display Excel Values directly on Form
  5. Database Connection String Property
  6. Source ConnectStr Property and ODBC
  7. Link External Tables with VBA
  8. Lost Links of External Tables
  9. MS-Access Live data in Excel
  10. MS-Access Live data in Excel-2

As you can see from the list above, methods 1 through 6 show different ways of bringing external data into Access without keeping the tables permanently linked to the database.

When working with dBase or FoxPro tables, the folder path where the table resides is treated as the database name.

If you’ve already read the second article, Opening dBase Files Directly, you should now have a good idea of what we are about to explore—namely, how to send output data into external databases without linking them to Microsoft Access.

Sample SQL for External dBase Table.

Before we dive into output operations, let’s take a closer look at a sample SQL statement that retrieves data from a dBase table through a query—without linking the table to the Access database.

Note: If you don’t already have a dBase table to test with, you can easily create one by exporting one or more of your Access tables into a separate folder on your disk. You don’t need to install a dBase application on your machine—the required ODBC driver files are already included with Microsoft Office.

SELECT Employees.* FROM Employees IN 'C:\MydBase'[DBASE IV;];

The SELECT query shown above will return all records from the Employees.dbf table located in the dBase database folder C:\MydBase. The text [DBASE IV;] specifies the database type and version. The clause

IN 'C:\MydBase' [DBASE IV;];

creates a direct connection to the Employees.dbf table—without establishing a permanent physical link. In other words, the data from Employees.dbf is accessible only through this query and not as a linked table in Access.

Up to this point, we have been focusing on how to bring data from external databases into Access without linking them. Now, let’s take it a step further and explore how to update or add data to these external databases.

Updating Data into an External dBase Table.

A sample SQL that updates an external dBase Table is given below:

UPDATE Products IN 'C:\MydBase'[DBASE 5.0;] SET Products.TARGET_LEV = 45 WHERE (((Products.TARGET_LEV)=40) AND ((Products.REORDER_LE)=10));

With the above SQL, we are updating the Products stock Target level to 45 from 40, for items with Re-order Level (Minimum Stock Level) is 10, and the current stock quantity target level is 40.

Appending Data into an External dBase Table.

Let us append some data from the Products_Tmp Table from the current MS-Access Database to the Products.dbf Table of C:\MydBase dBase Database.  The sample SQL is given below:

INSERT INTO Products
  SELECT Products_Tmp.*
  FROM Products_Tmp IN 'C:\MydBase'[DBASE 5.0;];

IN Clause and Query Property Setting

Source Database and Source Connect Str Properties.

Let us examine the Property Sheet of one of the above Queries to check for any indication about whether the SQL IN Clause setting is in there or not.

  1. Open one of the above Queries in Design View.

  2. Display the Property Sheet of the Query. Press F4 or ALT+Enter to display the property sheet and make sure that it is the Query Property Sheet. Under the Title of the Property Sheet, there will be a description: Selection Type Query Property.

  3. You may click on an empty area to the right of the Table on the Query Design surface to make sure that the Property Sheet displayed is the Query's Property Sheet, not the Table or Query Column Property Sheet. Check the sample image given below.

  4. Check the Source Database and Source Connect Str Property Values. If you find it difficult to memorize the correct syntax of the IN Clause in SQL, then you can populate the respective values in these properties of the Query as shown. This will automatically insert the Connection String with the correct syntax in the SQL.

  5. You can find the correct syntax for Access, Excel, Paradox, and ODBC connection strings for IBM iSeries machines, SQL Server, etc., from the above-quoted Articles.

Caution:

While the above methods offer convenient ways to work with external tables without permanently linking them to an Access database, relying on this approach too heavily can cause problems down the line if not managed carefully. To avoid confusion or data management issues, it is essential to maintain proper documentation of these queries and keep them safely stored for future reference.

Constant Location Reference Issues?

Let’s consider the case of an external Microsoft Access database. The SQL example below demonstrates how to append data directly into the Employees table of another Access database located on a LAN server. This type of operation is commonly performed on a scheduled basis—daily, weekly, or at other regular intervals.

INSERT INTO Employees IN 'T:\Sales\mdbFolder\Database1.accdb' 
SELECT Employees_tmp.*
FROM Employees_tmp;

Everything works smoothly, and over time, you may even forget about this particular query—or others like it. After six months, suppose you decide to shift or copy the databases from their current folder into a new location on the server (say, T:\Export\mdbFolder), while leaving a copy in the old folder as a backup. The database seems to function perfectly in the new location, no errors appear, and the users are satisfied.

However, some of your queries still contain the original connection strings hard-coded in their SQL statements. Since these were never updated to point to the new folder, the queries continue working against the old database copy in ...\Sales..., instead of the intended ...\Export... location. When users eventually report data discrepancies, it may not immediately occur to you that the culprit is the IN clause of your SQL. By the time you discover the oversight, you may already have wasted hours—or even days—troubleshooting the wrong problem.

Despite this drawback, the method remains useful when external databases are needed only occasionally. If the frequency of use is minimal, it is often better than keeping the external tables permanently attached to the front-end.

Share:

Users and Groups Listing from Workgroup Information File

Introduction

How about taking a printout of Users and Groups from the active Workgroup Information File (the Microsoft Access Security File)?

This applies only to users of Microsoft Access 2003 or earlier databases that were implemented with Access Security. Such databases can still be opened and used in Access 2007 or Access 2010 without conversion.

To link to the Workgroup Information File (.mdw) from Access 2007, you can run the Workgroup Administrator program. For step-by-step instructions, please refer to the article: Running Workgroup Admin Program from Access 2007.

On a personal note, I am not particularly fond of the frequent version changes in Access. While new features are always exciting to explore, they often come at the cost of what we have already learned and implemented. For example, I still wonder why the familiar Menus and Toolbars were reorganized and rebranded as the Ribbon in Access 2007. Such changes often add confusion and waste time, forcing users to relearn tasks they could once do quickly. By the time users finally become comfortable with the new interface, a newer version appears—and the cycle starts all over again.

Upgrades are always welcome—provided they correct the drawbacks and bugs of earlier versions and implement genuine enhancements that users can easily locate and benefit from.

Coming back to the topic of printing Users and Groups from the active Workgroup Information File, Microsoft Access already provides a built-in option. The only limitation is that the listing is sent directly to the printer, which may not be ideal.

To use this option in Access 2003 or earlier:

Select Tools → Security → Users and Group Accounts → Users → Print Users and Groups.

In Access 2007 (with an Access 2003 or earlier database open):

Go to Database Tools → Administer → Users and Permissions → User and Group Accounts → Users → Print Users and Groups.

But why waste stationery when there’s a more flexible option? You can generate a list of Users and Groups and save it to a text file on your disk instead. Below is a simple VBA procedure you can use for this purpose. Copy and paste the following code into a Standard Module, then save and run it:

Database UsersList() Function.

Public Function UsersList() 
'------------------------------------------------------------- 
'Author : a.p.r. pillai 
'Date   : Oct 2011 
'Rights : All Rights Reserved by www.msaccesstips.com 
'Remarks: Creates a list of Users & UserGroups from the 
'       : active Workgroup Information File and saves 
'       : the list into a text file: UserGroup.txt 
'       : in the current database path 
'------------------------------------------------------------- 
Dim wsp As Workspace, grp As Group, usr As User 
Dim fs As Object, cp_path As String 
Dim a, txt 
Const ten As Integer = 10 

cp_path = CurrentProject.Path 
Set wsp = DBEngine.Workspaces(0) 
'Create a Text file: UserGroup.txt with FileSystemObject 
Set fs = CreateObject("Scripting.FileSystemObject") 
Set a = fs.CreateTextFile(cp_path & "\UserGroup.txt", True) 

'Write headings 
a.writeline "SYSTEM-DEFAULT GROUPS" 
a.writeline "-----------------------" 
a.writeline ("User-Groups  User-Names") 
a.writeline ("-----------  ----------") 

'List Default Admins & Users Group First 
For Each grp In wsp.Groups 
   txt = grp.Name 
   If txt = "Admins" Or txt = "Users" Then 
     a.writeline txt & Space(ten - Len(grp.Name)) & Space(3) & "..." 
     For Each usr In grp.Users 
        txt = Space(Len(grp.Name) + (ten - Len(grp.Name))) & Space(3) & usr.Name 
        a.writeline txt 
     Next: a.writeline crlf 
   End If 
Next 

'Groups, except Default Admins & Users 
a.writeline "ADMINISTRATOR-DEFINED GROUPS" 
a.writeline "----------------------------" 
a.writeline ("User-Groups  User-Names") 
a.writeline ("-----------  ----------") 

For Each grp In wsp.Groups 
   txt = grp.Name 
   If txt = "Admins" Or txt = "Users" Then 
      GoTo nextitem 
   Else 
      a.writeline txt & Space(ten - Len(grp.Name)) & Space(3) & "..." 
      For Each usr In grp.Users 
         txt = Space(Len(grp.Name) + (ten - Len(grp.Name))) & Space(3) & usr.Name 
         a.writeline txt 
      Next: a.writeline crlf 
   End If 
nextitem: 
Next 
a.Close 
'Open UserGroup.txt file with the list User list. 
Call Shell("Notepad.exe " & CurrentProject.Path & "\UserGroup.txt", vbNormalFocus) 

End Function

Running UsersList() Function

You can run this program either directly from the Immediate Window (Debug Window) or by calling it from the Click event of a Command Button on a Form.

When executed, the program will create a text file named UserGroup.txt in the same folder where the current database resides. Once the file is generated, it will automatically open in Windows Notepad for review.

Keep in mind that each time you run this program, the existing file will be overwritten. If you would like to preserve previous listings, remember to rename or move the file to a safe location before running the procedure again.

The result of a sample run of the program is given below:

If you need a printout of Users and Groups, then you may print it from the text file.

Share:

Access Security Key Diagram

Introduction - Access 2003.

Implementing Microsoft Access Security is a serious undertaking. Although this feature was deprecated starting with Access 2007, thousands of developers still rely on it in their applications. Microsoft’s documentation spans several pages, detailing the intricacies of this system, and it can be difficult to visualize how all the components work together to form the complete security framework.

To clarify this, I have created a diagram that consolidates the key elements of Microsoft Access Security. This visual overview provides a general understanding of the components involved and how they fit into the overall security structure.

Maintaining proper security is critical—not only to regulate user roles but also to safeguard data, protect the integrity of database objects, and ensure the security of VBA code.

For a deeper dive, you can explore the collection of articles on Microsoft Access Security available under the Security sub-menu on the main menu bar of this site.

Microsoft Access Security - Two Sections.

  1. The first part of the Security elements (Workgroup File Id elements and User/Group Names, Personal IDs, and Passwords) resides within the Workgroup Information File.

  2. Object-level access rights information that resides within the Database forms the second part.

When both parts are combined, consisting of fourteen security elements, it becomes the full security key of a User.  See the diagram given below:


Workgroup FileID.

The first three elements—Workgroup Name, Organization, and Workgroup ID—serve as the unique identifiers of a Workgroup Information File. It is essential to keep this information safely stored after creating the file. If the file is ever lost, you will need these exact details to recreate it. Microsoft Access uses this combination of values to distinguish one Workgroup Information File from another.

User Specific Credentials.

The next three elements—User or Group Name, Personal ID, and Password—are user-specific credentials. Group accounts, however, contain only a Group Name and Personal ID; they do not use passwords. It is crucial to maintain a secure record of all User and Group Names along with their corresponding Personal IDs.

Group accounts are primarily a way to organize users, allowing access privileges to be assigned at the group level. Any user added to a group automatically inherits that group’s access permissions.

When you create a new Workgroup Information File, it includes, by default:

  • One User Account: Admin

  • Two Group Accounts: Admins and Users

The Admin user account is automatically a member of both groups. While the two group accounts (Admins and Users) cannot be deleted, new user accounts you create will always be added to the Users group by default. Similarly, the Admin user account itself cannot be deleted, but as a security precaution, it can be removed from the Admins group.

Members of the Admins group hold full administrative authority. They can assign permissions to objects and transfer ownership of objects (except the database object) to other user or group accounts.

Database Owner.

An important point to remember is that the owner of a database or object (i.e., the user who created it) has the same privileges as an administrator, specifically as a member of the Admins group. The owner of an object can assign permissions to other users or transfer ownership of that object to another user, just as an administrator would.

However, ownership of a database itself cannot be transferred. If someone wishes to assume ownership of a database, they must create a new database and then import all the objects from the original database. Provided they have sufficient permissions to do so.

Share:

Updating Sub-Form Recordset from Main Form

Introduction

A Subform on a Main Form is a common design pattern used to display multiple related records alongside a single record from the main form. For example, order details linked to orders, bank accounts with their transactions, or student IDs with their mark lists. In short, nearly all databases with one-to-many relationships use this approach, as it provides a convenient way to view a large amount of related information in one place.

When a form is opened with a table or query as its record source, Access loads a parallel Recordset in memory, with each record uniquely bookmarked. This allows us to search and navigate through the virtual recordset without directly interacting with the underlying table or query. However, when a record is added or updated in this virtual recordset, the change is automatically saved back to the actual table. This in-memory recordset is known as the form’s RecordsetClone.

Working with Recordset Clone.

The sample VBA code below demonstrates how to work with a form’s RecordsetClone to locate a record based on specific criteria. In this example, we search for an order using its ProductID and then move the form’s current record pointer to that record:

Private Sub FindPID_Click()
'Find Record matching Product ID
Dim m_find, rst As Recordset

'validation check of search key value
m_find = Me![xFind]
If IsNull(m_find) Then
   Me.FilterOn = False
   Exit Sub
End If

'validation check of search key value
If Val(m_find) = 0 Then
  MsgBox "Give Product ID Number..!"
   Exit Sub
End If

'Find a record that matches the ProductID
'and make that record current using the recordset bookmark.
If Val(m_find) > 0 Then
   Set rst = Me.RecordsetClone 'declare the recordset of the form
   rst.FindFirst "ProductID = " & m_find
   If Not rst.NoMatch Then '<if record found then make that record current
      Me.Bookmark = rst.Bookmark
   End If
   rst.Close
End If

End Sub

We already have a blog post demonstrating how to search and filter data on a form using the RecordsetClone object. You can check that article [here].

In the earlier example, we worked with the RecordsetClone of the main form directly from its own module. But what if we need to access the RecordsetClone of a subform from the main form?

The key point to remember is this:

  • The subform displays only those records that are related to the current record on the main form.

  • Therefore, the subform’s RecordsetClone will contain only this filtered set of records—not all records from the underlying table or query.

By contrast, the RecordsetClone of the main form always includes all records from its record source, making it possible to search or update across the entire Recordset. For the subform, however, you can work only with the records currently visible in the subform for the active main form record.

Accessing Sub-Form Recordset from Main Form.

Let us try an example to learn how to access the sub-form record set from the main form and update records.

  1. Import the following two Tables from the Northwind (or Northwind.mdb) database:

    • Orders
    • Order Details

    Create a New Field for testing purposes.

  2. Open the Order Details Table in the design view.

  3. Add a new field: Sale Value with Data Type: Number and Field Size: Double.

  4. Save the Order Details Table with the new field.

  5. Design the Main form for the Orders Table in column format.

    If you have used the Form Wizard and created a Split Form, then delete the Datasheet sub-form or table (Access 2007). Display the Property Sheet of the Form, find the Default View property, and change the Split Form value to Single Form.

    Create a Sub-Form.

  6. Design a Datasheet Sub-Form for Order Details Table.

  7. Expand the Footer of the Sub-Form and create a Text box there.

  8. Change the Name Property value to TotSale.

  9. Write the expression =Sum([Sale Value]) in the Control Source property.

  10. Save and close the Form with the name: Order Details.

  11. Insert the Order Details sub-form in the Detail Section of the Orders Form below the Orders Form controls. See the image given below:

    Sub-Form Link with the Main form.

  12. While the Sub-Form is still in the selected state, display its Property Sheet (F4).

  13. Set the Link Master Field property value to [Order ID].

  14. Change the Link Child Field property value to [Order ID].

  15. Add a Command Button above the sub-form as shown on the design above

    .
  16. Display the Property Sheet of the Command Button (F4 or Alt+Enter.

  17. Change the Name property value to cmdUpdate

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

  19. Click on the Build (...) button at the right end of the property to open the VBA Module of the Form.

  20. Copy and paste the following VBA Code into the VBA Module, overwriting the skeleton lines of the Sub-Routine there.

    Sub-form Module Code.

    Private Sub cmdUpdate_Click()
    Dim rst As dao.Recordset
    Dim m_UnitPrice As Double
    Dim m_Discount As Double
    Dim m_Quantity As Long
    Dim m_SaleValue As Double
    
    'Address the recordset on the Sub-Form [Order Details]
    Set rst = [Order Details].Form.RecordsetClone
    rst.MoveFirst
    Do While Not rst.EOF
        m_UnitPrice = rst![Unit Price]
        m_Discount = rst![Discount]
        m_Quantity = rst![Quantity]
        m_SaleValue = m_Quantity * ((1 - m_Discount) * m_UnitPrice)
        rst.Edit
        rst![SaleValue] = m_SaleValue
        rst.Update
        [Order Details].Form.Bookmark = rst.Bookmark
    rst.MoveNext
    Loop
    rst.Close
    
    Set rst = Nothing
    
    End Sub
  21. Create a Textbox to the right of the Command Button.

  22. Set the Caption property value of the Child Label to Order Value:

  23. Write the expression =[Order Details].[Form]![totSale]. This expression brings the Summary Value from the Text box, in the Footer Section of the sub-form, into the Order Form.

  24. Save and close the Orders Form.

    Open the Order Form.

  25. Open the Orders Form in Normal View.
  26. If the Sale Value column is not visible in the datasheet, use the bottom scroll bar to move to the right. Locate the Sale Value column, then click and hold the mouse button, drag the column to the left, and drop it within the visible area.

    Now you can see that the subform displays the records related to the current Order ID on the main form. However, the new text box we created to the right of the command button is still empty because the [Sale Value] field on the datasheet has not yet been updated.

  27. Click on the Command Button to calculate and update the Sale Value of each record on the Datasheet Sub-Form.

    Now you will see that the Sale Value column of all records on the subform has been updated, and the summary value of these records is displayed in the text box to the right of the command button. Only the Order Detail records related to the current Order ID on the Orders form are updated. If you move to another record in the Orders table, its related Sale Value records will remain unchanged until you click the command button again.

    In the code, the statement:

    Set rst = [Order Details].Form.RecordsetClone

    creates a reference to the RecordsetClone object of the subform [Order Details]. The following lines calculate the Sale Value (after applying any discount) and update it into the new field [Sale Value] in the Order Details table.

    The line:

    [Order Details].Form.Bookmark = rst.Bookmark

    sets the subform’s Bookmark equal to the current record’s Bookmark in the recordset clone. This ensures that the record being processed in the recordset clone also becomes the current record on the subform.

    If the subform contains many records, you may notice visible movement of the cursor as it rapidly shifts from one record to another, starting at the first record and progressing through to the last, while the update operation runs.

  • Macro and Temporary Variables
  • Easy-read Reports
  • Top N Records in Query
  • Attachment field in Access 2007
  • Embedded Macros in Access 2007
Share:

Easy Reference Access2003 Commands in Access2007

Introduction.

If you have been working with Access 2003 Menus and Toolbars, you know how easy design tasks can be when everything is familiar and right where you expect it. Work moves smoothly—until one day you hear some exciting news: Microsoft Access 2007 has been released. You can’t wait to try out its new features. With all the experience you’ve gained in Access 2003, you feel ready to explore and learn even more.

Finally, the day arrives—you install Access 2007 and begin exploring the new interface.

But after a few days, discomfort sets in. The Menus and Toolbars you relied on are gone, replaced with something called the Ribbon. Suddenly, you’re not sure where to find the commands you once used instinctively. Design tasks that were quick and easy in Access 2003 now feel awkward and slow. You realize that creating Forms and Reports is not going to be as straightforward as before—at least not until you become familiar with the new layout.

At this point, you’re ready to accept any help you can get to get back on track. Microsoft anticipated this struggle, too—and they included something to ease the transition, as long as you already know your way around Access 2003.

AccessMaps.xls File.

There is an Excel workbook named accessmaps.xls that displays the Access 2003 and Access 2007 menus and toolbar options side by side. On the left, you will see the familiar Access 2003 menu options, and in the corresponding right column, you will find their equivalents in Access 2007. This makes it much easier to locate the new Ribbon commands based on your prior knowledge of Access 2003.

To get started, locate the accessmaps.xls file and save a copy in a place where you can easily access it—your desktop is a good option.

Do the following to get the file:

  1. Click on the Access Help button (the circular button with a white question mark in the blue background at the right end of the Menu Bar).  Microsoft Access Help window opens.

  2. Click on the Getting Started option, under the Table of Contents, to open the sub-topics.

  3. Find Reference: Locations of Access 2003 commands in Access 2007 and click on it to open the details page in the right window.

  4. Click on the New locations of familiar commands hyperlink to send you to the bottom of the document, or use the vertical scroll bar to move to the bottom of the document.

  5. Click on the Access Ribbon mapping workbook, and a File Download dialog box opens up asking whether you want to open or save the accessmaps.xls file.

  6. You'd better save a copy to your Desktop so that whenever you want it, you can find it easily.

If you could not locate the AccessMaps.xls file through the above procedure, then download it from the following link:


Share:

IIF vs SWITCH Function in MS-Access

Introduction.

The IIF() Function.

The IIF() Function definition is reproduced here from Microsoft Visual Basic for Applications Reference below:

The IIf Function returns one of two parts, depending on the evaluation of an expression.

Syntax: IIf(logical expression, true part, false part)

The IIf function syntax has these named arguments:

Part Description
Expression Required. The expression you want to evaluate.
True part Required. Value or expression returned if the expression evaluates to True.
False part Required. Value or expression returned if the expression is False.

Remarks

The IIf expression always evaluates both the True part and the False part, even though it will return only one of them. Because of this, you should be aware of the side effects. For example, if evaluating to false in a division by zero error case, an error occurs even if the expression is True.

Example:

This example uses the IIf() function to evaluate the TestMe parameter of the CheckIt() Function and returns the word "Large" if the amount is greater than 1000; otherwise, it returns the word "Small".

Function CheckIt(TestMe As Integer)
      CheckIt = IIf(TestMe > 1000, "Large", "Small") 
End Function 

Courtesy: Microsoft Access Help

Let us expand the above function to check a series of expressions to return one of the values among them.

Function CheckIt(TestMe As Integer)
      CheckIt = IIF(TestMe > 0 AND TestMe < 256, "Byte", _
      IIF(TestMe > 255 AND TestMe < 32768,"Integer","Large")) 
 End Function 

As you can see from the above example, for testing each expression, we can nest the IIF() function one within another, when two or more expressions are evaluated, and the parentheses must be paired properly.  This is where we face problems while using this function in Query columns or in criteria rows, etc.

If we need a valid value to be returned when none of the expressions evaluated to True (in the above example, the text "Large"), then IIF() is the correct solution; otherwise, we have a better function, Switch().

The Switch Function.

The Switch() Function is simple to use without nesting expressions like IIF().  Let us rewrite the CheckIt() Function, using the Switch() function, to see how simple it is.

Function CheckIt(TestMe As Integer) 
    CheckIt = Switch(TestMe > 0 AND TestMe < 256, "Byte", _
TestMe > 255 AND TestMe < 32768,"Integer") 

End Function 

The above function does the same thing, but if none of the expressions evaluate to True, the result returned in the CheckIt variable is Null instead of the text "Large".  If you want to check the returned result for Null and replace Null with the text "Large," then rewrite the expression as below:

CheckIt = NZ(Switch(TestMe > 0 AND TestMe < 256, "Byte",TestMe > 255 AND _
TestMe < 32768,"Integer"),"Large")

OR

x = Switch(TestMe > 0 AND TestMe < 256, "Byte", _
TestMe > 255 AND TestMe < 32768,"Integer")

CheckIt = Nz(x,"Large")

If you are using the Switch() Function in a Query column or criteria row, then the first example will be used with Switch() enveloped in Nz(). 

I think it is easier and more compact to use the Switch() Function when compared with IIF(), which needs to repeat the function name IIF with balancing of several parentheses when several expressions are evaluated.

Usage in a sample Query:
UPDATE Employees SET Employees.Designation = Switch(Employees.Designation IS NULL,'UNKNOWN')
WHERE ((Employees.FirstName IS NOT NULL));

See the Switch() Function definition given below for details, taken from the Microsoft Access Help Document.

Switch Function Evaluates a list of expressions and returns a Variant value or an expression associated with the first expression in the list that is True.

Syntax;

Switch(expr-1, value-1[, expr-2, value-2 … [, expr-n,value-n]])

The Switch function syntax has these parts:

Part Description
expr Required. Variant expression you want to evaluate.
value Required. Value or expression to be returned if the corresponding expression is True.

Remarks:

The Switch function argument list consists of pairs of expressions and values. The expressions are evaluated from left to right, and the value associated with the first expression to evaluate to True is returned. If the parts aren't properly paired, a run-time error occurs. For example, if expr-1 is True, the Switch returns value-1. If expr-1 is False, but expr-2 is True, the Switch returns value-2, and so on.

Switch returns a Null value if: None of the expressions are True. The first True expression has a corresponding value that is Null. Switch evaluates all of the expressions, even though it returns only one of them. For this reason, you should watch for undesirable side effects. For example, if the evaluation of any expression results in a division by zero error, an error occurs.

Example:

This example uses the Switch function to return the name of a language that matches the name of a city.

Function MatchUp (CityName As String)

    Matchup = Switch(CityName = "London", "English", CityName _
                    = "Rome", "Italian", CityName = "Paris", "French")
End Function

Earlier Post Link References:

Share:

Preparing Rank List

Introduction

We often use an Autonumber field in a table to automatically generate a unique sequence number for each record entered. This field can serve as the Primary Key. In related tables, a corresponding field can be designated as a Foreign Key to establish a relationship with the parent table, enabling combined views of related data forms, queries, or reports.

Even in a stand-alone table that is not part of any relationship, using an autonumber field is beneficial. It allows records to be sorted in the order they were entered, which is especially useful when the table does not include a date/time field for data entry.

The Running Sum Property

However, when you pull an Autonumber field into a query with any filter criteria, its values may no longer appear in consecutive order. If you intend to use the autonumber field for sequence numbers on a report, this isn’t a problem. You can simply add a textbox in the Detail Section of the report, set its Control Source to =1, and set the Running Sum property to Yes—Access will automatically number the report rows sequentially.

If the query is being used as a data source for a Data View or to create an output table with properly sequenced numbers, we need additional techniques to achieve correct numbering. In an earlier blog post, I shared a Function to generate sequence numbers for filtered query results. You can refer to it here: [Auto-numbering in Query Column].

The above discussion introduces the concept of assigning sequence numbers across all records in a query. But what if we want separate sequence numbers for each category or group of records?

For example:

  • In a school, the headmaster may want to identify the highest-ranked holder in each subject for a particular class or school.

  • Or, find the top 5 state-level rank holders in each subject across schools.

  • In a procurement scenario, you want to identify the lowest quotes for each item from multiple suppliers.

To achieve this, we can write a VBA function that works on a report source table, adding a new field (e.g., Rank) to store the ranking. First, the data table must be prepared by consolidating information from input tables or queries.

Below is a sample image of a student’s table with several subjects, ready for running the Rank-List program.


The Rank List.

Our task is to organize the above data in a specified order and assign Rank numbers (1, 2, 3, …) based on the highest values in the Score field, sorted in descending order. This ranking should be done separately for each group of subjects in the Event field, which is sorted in ascending order.

The rank list is being prepared for Class No. 2, covering students from several schools in the area.

Table Name: SchoolTable

Sorting Order: The Event (Ascending), Score (Descending), School (Ascending) – School field sorting optional

Function Call Syntax: RankList(TableName, Primary Sorting Field, Value Field, Optional Third Sorting Field)

Sample Function Call: RankList(“SchoolTable”, ”Events”, ”Score”, ”School”)

The RankList() Function

The RankList() Function Code is given below:

Public Function RankList(ByVal TableName As String, _
                         ByVal Grp1Field As String, _
                         ByVal ValueField As String, _
                         Optional ByVal Grp2Field As String)
'-----------------------------------------------------------------
'Preparing Rank List
'Author : a.p.r.pillai
'Date   : August 2011
'Rights : All Rights Reserved by www.msaccesstips.com
'Remarks: Free to use in your Projects
'-----------------------------------------------------------------
'Parameter List:
'TableName  : Source Data Table
'Grp1Field  : Category Group to Sort on
'ValueField : On which to determine the Rank Order
'Grp2Field  : Sorted on for values with the same rank number
'-----------------------------------------------------------------
Dim db As Database, rst As Recordset, curntValue, prevValue
Dim srlRank As Byte, curntGrp1, prevGrp1
Dim prevGrp2, curntGrp2
Dim fld As Field, tbldef As TableDef, idx As Index
Dim FieldType As Integer

On Error Resume Next

Set db = CurrentDb
Set rst = db.OpenRecordset(TableName, dbOpenTable)

'Check for presence of Table Index "MyIndex"
'if not found then create
rst.Index = "MyIndex"

If Err > 0 Then
   Err.Clear
   On Error GoTo RankList_Err

Set tbldef = db.TableDefs(TableName)
Set idx = tbldef.CreateIndex("MyIndex")

FieldType = rst.Fields(Grp1Field).Type
Set fld = tbldef.CreateField(Grp1Field, FieldType)
idx.Fields.Append fld

FieldType = rst.Fields(ValueField).Type
Set fld = tbldef.CreateField(ValueField, FieldType)
fld.Attributes = dbDescending ' Line not required for sorting in Ascending
idx.Fields.Append fld

FieldType = rst.Fields(Grp2Field).Type
Set fld = tbldef.CreateField(Grp2Field, FieldType)
idx.Fields.Append fld

rst.Close

tbldef.Indexes.Append idx
tbldef.Indexes.Refresh
Set rst = db.OpenRecordset(TableName, dbOpenTable)
rst.Index = "MyIndex"
End If

curntGrp1 = rst.Fields(Grp1Field)
prevGrp1 = curntGrp1
curntValue = rst.Fields(ValueField).Value
prevValue = curntValue

Do While Not rst.EOF
     srlRank = 1
     Do While (curntGrp1 = prevGrp1) And Not rst.EOF
       If curntValue < prevValue Then
          srlRank = srlRank + 1
       End If
          rst.Edit
          rst![Rank] = srlRank
          rst.Update
          rst.MoveNext
          If Not rst.EOF Then
             curntGrp1 = rst.Fields(Grp1Field)
             prevValue = curntValue
             curntValue = rst.Fields(ValueField).Value
          End If
     Loop
     prevGrp1 = curntGrp1
     prevValue = curntValue
Loop
rst.Close
'Delete the Temporary Index
tbldef.Indexes.Delete "MyIndex"
tbldef.Indexes.Refresh

Set rst = Nothing
Set db = Nothing

RankList_Exit:
Exit Function

RankList_Err:
MsgBox Err & " : " & Err.Description, , "RankList()"
Resume RankList_Exit

End Function

The Code Creates a Temporary Index

In the first part of the program, we check whether an index named MyIndex exists in the input table. If the index is not found, the program creates it temporarily for use during the ranking process. Once the rank list has been generated in the table, the temporary index MyIndex is deleted.

The result of running the function:

RankList("SchoolTable", "Events", "Score", "School")

is shown below. Observe the Rank field values, which are assigned based on the Score values within each Event group.

In the Accounting event, the first two ranks are awarded to City View School, the third rank goes to Krum School, and the fourth, fifth, and sixth ranks are assigned to Holiday School. The seventh rank is shared by City View and Holiday Schools.

Similarly, the events Current Events and Social Studies are also ranked in order, with each school receiving ranks based on its scores within the respective event.

Download.


Download Demo RankList.zip


  1. Auto-Numbering in Query Column
  2. Product Group Sequence with Auto-Numbers.
  3. Preparing Rank List.
  4. Auto-Number with Date and Sequence Number.
  5. Auto-Number with Date and Sequence Number-2.
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