21. Using Access as a Back End to Enhance Multiuser Access to Data

The example near the end of Chapter 20, “Text File Processing,” proposed a method for storing 683 million records in an Excel worksheet. At some point, you need to admit that even though Excel is the greatest product in the world, there is a time to move to Access and take advantage of the Access Multidimensional Database (MDB) files.

Even before you have more than one million rows, another compelling reason to use MDB data files is to allow multiuser access to data without the headaches associated with shared workbooks.

Microsoft Excel offers an option to share a workbook, but you automatically lose a number of important Excel features when you share one. After you share a workbook, you cannot use automatic subtotals, pivot tables, Group and Outline mode, scenarios, protection, Autoformat, Styles, Pictures, Add Charts, or Insert Worksheets.

By using an Excel VBA front end and storing data in an MDB database, you have the best of both worlds. You have the power and flexibility of Excel and the multiuser access capability available in Access.


Note

MDB is the official file format of both Microsoft Access and Microsoft Visual Basic. This means that you can deploy an Excel solution that reads and writes from an MDB to customers who do not have Microsoft Access. Of course, it helps if you as the developer have a copy of Access because you can use the Access front end to set up tables and queries.



Caution

The examples in this chapter make use of the jet engine for reading from and writing to the Access database. The jet engine works with access data stored in Access 97 through 2010. If you are sure that all of the people running the macro will have Office 2007 or newer, you could instead use the ACE engine.

The troubling issue is that when this book goes to press, Microsoft is not committed to releasing 64-bit versions of either the jet or ACE ADO interface. This is perplexing because it would leave hundreds of thousands of Access applications without a path to work in 64-bit Office. This will either prevent people from upgrading to 64-bit Office or force people into SQL Server.

To use code in this chapter with 64-bit versions of Office, type Microsoft.Jet.OLEDB and 64-bit into a search engine to see whether Microsoft has relented and provided a 64-bit version.

If you are running 64-bit Excel, you might have to switch over to SQL Server Express for storing this data. See examples at the end of the chapter for adapting this code for SQL Server.


ADO Versus DAO

For several years, Microsoft recommended data access objects (DAO) for accessing data in external database. DAO became very popular, and a great deal of code was written for it. When Microsoft released Excel 2000, they started pushing ActiveX data objects (ADO). The concepts are similar, and the syntax differs only slightly. I use ADO in this chapter. Realize that if you start going through code written a decade ago, you might run into DAO code. Other than a few syntax changes, the code for both ADO and DAO looks similar.

If you discover that you have to debug some old code using DAO, check out the Microsoft Knowledge Base articles that you can find at the following address, which discuss the differences: http://support.microsoft.com/kb/225048.

The following two articles provide the Rosetta Stone between DAO and ADO. The ADO code is shown at http://support.microsoft.com/kb/q146607.

The equivalent DAO code is shown at http://support.microsoft.com/kb/q142938.

To use any code in this chapter, open the VB Editor. Select Tools, References from the main menu, and then select Microsoft ActiveX Data Objects Library from the Available References list, as shown in Figure 21.1.

image

Figure 21.1. To read or write from an Access MDB file, add the reference for Microsoft ActiveX Data Objects Library or higher.


Tip

If you have Vista or newer, you will have access to version 6.0 of this library. If you will be distributing the application to anyone who is still on Windows XP, you should choose version 2.8 instead.


The remainder of this chapter gives you the code necessary to allow the application included in the previous case study to read or write data from the tblTransfer table.

The Tools of ADO

You encounter several terms when using ADO to connect to an external data source.

Recordset—When connecting to an Access database, the recordset will either be a table in the database or a query in the database. Most of the ADO methods will reference the recordset. You might also want to create your own query on-the-fly. In this case, you would write a SQL statement to extract only a subset of records from a table.

Connection—Defines the path to the database and the type of database. In the case of Access databases, you specify that the connection is using the Microsoft Jet Engine.

Cursor—Think of the cursor as a pointer that keeps track of which record you are using in the database. There are several types of cursors and two places for the cursor to be located (described in the following bullets).

Cursor type—A dynamic cursor is the most flexible cursor. If you define a recordset and someone else updates a row in the table while a dynamic cursor is active, the dynamic cursor will know about the updated record. Although this is the most flexible, it requires the most overhead. If your database doesn’t have a lot of transactions, you might specify a static cursor—this type of cursor returns a snapshot of the data at the time the cursor is established.

Cursor location—The cursor can be located either on the client or on the server. For an Access database residing on your hard drive, a server location for the cursor means that the Access Jet Engine on your computer is controlling the cursor. When you specify a client location for the cursor, your Excel session is controlling the cursor. On a very large external dataset, it would be better to allow the server to control the cursor. For small datasets, a client cursor is faster.

Lock type—The point of this entire chapter is to allow multiple people to access a dataset at the same time. The lock type defines how ADO will prevent crashes when two people try to update the record at the same time. With an optimistic lock type, an individual record is locked only when you attempt to update the record. If your application will be doing 90 percent reads and only occasionally updating, then an optimistic lock is perfect. However, if you know that every time you read a record you will soon update the record, then you would use a pessimistic lock type. With pessimistic locks, the record is locked as soon as you read it. If you know that you will never write back to the database, you can use a read-only lock. This allows you to read the records without preventing others from writing to the records.

The primary objects needed to access data in an MDB file are an ADO connection and an ADO recordset.

The ADO connection defines the path to the database and specifies that the connection is based on the Microsoft Jet Engine.

After you have established the connection to the database, you usually will use that connection to define a recordset. A recordset can be a table or a subset of records in the table or a predefined query in the Access database. To open a recordset, you have to specify the connection and the values for the CursorType, CursorLocation, LockType, and Options parameters.

Assuming that you have only two users trying to access the table at a time, I generally use a dynamic cursor and an optimistic lock type. For large datasets, the adUseServer value of the CursorLocation property allows the database server to process records without using up RAM on the client machine. If you have a small dataset, it might be faster to use adUseClient for the CursorLocation. When the recordset is opened, all the records are transferred to memory of the client machine. This allows faster navigation from record to record.

Reading data from the Access database is easy. You can use the CopyFromRecordset method to copy all selected records from the recordset to a blank area of the worksheet.

To add a record to the Access table, use the AddNew method for the recordset. You then specify the value for each field in the table and use the Update method to commit the changes to the database.

To delete a record from the table, you can use a pass-through query to delete records that match a certain criteria.


Note

If you ever find yourself frustrated with ADO and think, “If I could just open Access, I could knock out a quick SQL statement that will do exactly what I need,” then the pass-through query is for you. Rather than use ADO to read through the records, the pass-through query sends a request to the database to run the SQL statement that your program builds. This effectively enables you to handle any tasks that your database might support but that are not handled by ADO. The types of SQL statements handled by the pass-through query are dependent on which database type you are connecting to.


Other tools are available that let you make sure a table exists or that a particular field exists in a table. You can also use VBA to add new fields to a table definition on-the-fly.

Adding a Record to the Database

Going back to our case study earlier in the chapter, the application we are creating has a userform where buyers can enter transfers. To make the calls to the Access database as simple as possible, a series of utility modules handle the ADO connection to the database. This way, the userform code can simply call AddTransfer(Style, FromStore, ToStore, Qty).

The technique for adding records after the connection is defined is as follows:

  1. Open a recordset that points to the table. In the code that follows, see the sections commented Open the Connection, Define the Recordset, and Open the Table.
  2. Use AddNew to add a new record.
  3. Update each field in the new record.
  4. Use Update to update the recordset.
  5. Close the recordset, and then close the connection.

The following code adds a new record to the tblTransfer table:

image

image

Retrieving Records from the Database

Reading records from the Access database is easy. As you define the recordset, you pass a SQL string to return the records in which you are interested.


Tip

A great way to generate the SQL is to design a query in Access that retrieves the records. While viewing the query in Access, select SQL View from the View drop-down on the Query Tools Design tab of the Ribbon. Access shows you the proper SQL statement required to execute that query. You can use this SQL statement as a model for building the SQL string in your VBA code.


After the recordset is defined, use the CopyFromRecordSet method to copy all the matching records from Access to a specific area of the worksheet.

The following routine queries the Transfer table to find all records where the Sent flag is not yet set to True. The results are placed on a blank worksheet. The final few lines display the results in a userform to illustrate how to update a record in the next section:

image

image

The CopyFromRecordSet method copies records that match the SQL query to a range on the worksheet. Note that you receive only the data rows. The headings do not come along automatically. You must use code to write the headings to Row 1. Figure 21.3 shows the results.

image

Figure 21.3. Range("A2").CopyFromRecordSet brought matching records from the Access database to the worksheet.

Updating an Existing Record

To update an existing record, you need to build a recordset with exactly one record. This requires that the user select some sort of unique key when identifying the records. After you have opened the recordset, use the Fields property to change the field in question and then the Update method to commit the changes to the database.

The earlier example returned a recordset to a blank worksheet and then called a userform frmTransConf. This form uses a simple Userform_Initialize to display the range in a large list box. The list box’s properties have the MultiSelect property set to True:

image

After the initialize procedure is run, the unconfirmed records are displayed in a list box. The logistics planner can mark all the records that have actually been sent, as shown in Figure 21.4.

image

Figure 21.4. This userform displays particular records from the Access recordset. When the buyer selects certain records and then chooses the Confirm button, you’ll have to use ADO’s Update method to update the Sent field on the selected records.

The code attached to the Confirm button follows. Including the ID field in the fields returned in the prior example is important if you want to narrow the information down to a single record:

image

image

Deleting Records via ADO

Like updating a record, the key to deleting records is being able to write a bit of SQL to uniquely identify the records to be deleted. The following code uses the Execute method to pass the Delete command through to Access:

image

Summarizing Records via ADO

One of Access’s strengths is running summary queries that group by a particular field. If you build a summary query in Access and examine the SQL view, you will see that complex queries can be written. Similar SQL can be built in Excel VBA and passed to Access via ADO.

The following code uses a fairly complex query to get a net total by store:

image

image

Other Utilities via ADO

Consider the application we created for our case study; the buyers now have an Access database located on their network but possibly no copy of Access. It would be ideal if you could deliver changes to the Access database on-the-fly as their application opens.


Tip

If you are wondering how you would ever coax the person using the application to run these queries, consider using an Update macro hidden in the Workbook_Open routine of the client application. Such a routine might first check to see whether a field does not exist and then add the field.


→ For details on the mechanics of hiding the update query in the Workbook_Open routine, see the “Using a Hidden Code Workbook to Hold All Macros and Forms” case study, p. 594.


Checking for the Existence of Tables

If the application needs a new table in the database, you can use the code in the next section. However, because we have a multiuser application, only the first person who opens the application has to add the table on-the-fly. When the next buyer shows up, the table may have already been added by the first buyer’s application.

This code uses the OpenSchema method to actually query the database schema:

image

Checking for the Existence of a Field

Sometimes you will want to add a new field to an existing table. Again, this code uses the OpenSchema method but this time looks at the columns in the tables:

image

Adding a Table On the Fly

This code uses a pass-through query to tell Access to run a Create Table command:

image

Adding a Field On the Fly

If you determine that a field does not exist, you can use a pass-through query to add a field to the table:

image

SQL Server Examples

If you have 64-bit versions of Office and if Microsoft does not provide the 64-bit Microsoft.Jet.OLEDB.4.0 drivers, you will have to switch over to using SQL Server or another database technology:

image

image

Next Steps

In Chapter 22, “Creating Classes, Records, and Collections,” you learn about the powerful technique of setting up your own Class module. With this technique, you can set up your own object with its own methods and properties.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset