Wednesday, September 22, 2010

How Can I Compact the Current Access Database in Code?

In my previous two posts: (What Does It Mean to Compact My Access Database? and How Do I Compact an Access Database?),  I discussed what compacting a database does and how to do it through the Access User Interface.  But it is also possible to use VBA code to do it as well.

Why would you want to use code?  Well, if you're making an application for others to use, you might want to give them a button to compact the database so they don't have to know the menu/ribbon selections.  You may also want to control when or how the compacting is done.

accDoDefaultAction Method
In Access 2003, it was possible compact the current database with the following code:
  • CommandBars("Menu Bar"). _
    Controls("Tools"). _
    Controls("Database utilities"). _
    Controls("Compact and repair database..."). _
    accDoDefaultAction
In Access 2007 and 2010, however, this method no longer works.  The command will still execute (modified slightly--notice the new first line and the ellipsis missing from the end?)
  • CommandBars("Menu Bar").Enabled = True
    CommandBars("Menu Bar"). _
    Controls("Tools"). _
    Controls("Database utilities"). _
    Controls("Compact and repair database"). _
    accDoDefaultAction
However, it will return with an error message: 
You cannot compact the open database by running a macro or Visual Basic code.

Well, that's not exactly true.

Send Keys Method
The Send Keys method is a way of sending keystrokes in code to the Access Interface.  Since the menu/ribbon is different depending on your context (and which version of Access you're using) the send keys argument can vary quite a bit.

First of all, you need to put the code in an Event Procedure behind a button on a form.  This will give us the form menu/ribbon context.

Access 2003: Sendkeys "%(TDC)", False
Access 2007: Sendkeys "%(FMC)", False
Access 2010: Sendkeys "%(YC)", False

I'm not really partial to that solution, though, because, as I said, I don't like to rely on a specific key sequence that can vary from context to context and version to version.

DAO CompactDatabase Method

A better solution, I think, is to use the DAO CompactDatabase method. The downside is that you can't use that on the current database. The workaround for that is to:

  1. Programmatically create a new, temporary database
  2. Copy several pre-created forms, macros and modules to this temp database
  3. Close the main database and launch temporary database with the /x switch which initiates the compact process.
  4. After compacting is done, close temp database and relaunch main database
On my website is a small sample database called "CompactDatabase.mdb" which illustrates this process.

The CompactDatabase method can also be used on an external database (in fact, it's easier to do so.) This is useful if you have split your database into a Front-End and a Back-End. You can use the CompactDatabase method directly from the Front-End against the Back-End. The BE, which stores the tables, is generally the one that needs compacting most. I've also got a sample called CompactBackEndDB.mdb which illustrates this.

The real usefulness of the DAO method is the safety and flexibility you have.  Instead of deleting the old database, you can rename it (say, by adding a date to the file name) so that you keep a backup.  In fact, the CompactDatabase method can also be used simply to create a backup of the database.

Compacting With ADO
For completeness, I should mention it's also possible to compact a database with ADO.  However, since I have no direct experience with it (I prefer DAO), I'll just give a Microsoft knowledge base article on the subject: http://support.microsoft.com/kb/230501/en-us.

Compacting Less Often
No discussion of compacting would be complete without addressing methods to reduce the need to compact in the first place.  I'll conclude this series next time with that.

.

Wednesday, September 15, 2010

How Do I Compact an Access Database?

In my previous post (What Does It Mean to Compact My Access Database?) I talked about what compacting an Access database is.  In this post, I'm going to discuss how to do it.  As with most things in Access, there are a number of ways, and the specifics change from version to version.

Compact On Close
I'm starting with Compact On Close to get it out of the way.  Few experienced Access developers recommend this option. 

Steps by version:
Access 2003: Tools > Options > General > Compact On Close (checkbox)
Access 2007: Office Button > Access Options > Current Database > Compact On Close (checkbox)
Access 2010: File > Options > Current Database > Compact On Close (checkbox)

While regular compacting can be good for performance, it's rare that a database needs to be compacted *every* time it closes.  If it does, there are steps you can take to reduce that necessity (I'll address that in a later post.) But the real problem with Compact on Close is the risk of database corruption.  Anytime you compact your database, there is a small risk of corrupting it.  When you do it every time you close the database, the changes increase simply due to its frequency. This is why most of us discourage the use of Compact On Close.

Compacting the Current Database in the UI
In Access, you can compact the current database from the Menu/Ribbon as long as you are the only one that has it open.

Steps by version:
Access 2003: Tools > Database Utilities > Compact and Repair Database...
Access 2007: Office Button> Manage > Compact and Repair Database
Access 2010: Database Tools tab > Compact and Repair Database

As I said in my last post, the compact process writes the records to a new database, deletes the old one, and renames the new one to the old name.  This is where the risk of corruption comes into it.  If something happens during the write process -- say, by a network interruption -- the new database can be corrupted and when the old one is deleted, you've lost your only good copy.

I have had this happen to me.  A database that's corrupted during compacting is, in my experience, corrupted beyond repair.  But I have to say that I believe later Access versions are better at ensuring corruption doesn't happen.  Still, there's always a risk.  That's why it's a good idea to make a copy of your database before compacting it.
 
Because network glitches can cause corruption, it is sometimes advisable (and faster) to copy a network database to a local drive, compact it, then copy it back up to the network.  This has the added benefit of preserving a the original while you compact it.
 

Compact Another Database in the Access UI

You can also compact a database that is not open (that is, the current database) in Access.  To do this, you must have Access open, but have no database open.

Steps by version:
*With No database open in Access*
Access 2003: Tools > Database Utilities > Compact and Repair Database...
Access 2007: Office Button> Manage > Compact and Repair Database
Access 2010: Database Tools tab > Compact and Repair Database

The steps are nearly the same as compacting the current database, but it will give you two dialog boxes, one (Database to Compact From) asking for the name of the file to be compacted, and a second (Compact Database Into) asking for the name you want to give to the new database.  Using this method, you *cannot* give it the same name as the original, so it safeguards your original database.  It also means, however, that you'll have to do the renaming manually.


Using Code

There are several ways to compact a database in code, both the current database and an external database.  There's enough here to fill a post of its own, so that's will I'll address next in How Can I Compact my Access Database Less Often?

.

Friday, September 10, 2010

What Does It Mean to Compact My Access Database?

Access databases are designed to grow dynamically as data is added.  Access will also create working space to manipulate data.  However, while it will grow dynamically, it does not shrink automatically when records are deleted or when it's data maniulation is done. 

What's more, as data is added and deleted, the database can become fragmented (much like a hard disk is fragmented), and records can be stored out of primary key order.  All of this can degrade the performance of your database, especially as it gets larger.

Compacting the database corrects these problems.

But before I get to that, it's important to understand exactly how compacting works because and existing file is not actually compacted.  Here's what actually happens:
  1. Access creates a new, blank database called db1.mdb (Access 2003-) or database1.accdb (Access 2007+).
  2. It writes the data in the original database to the new database, doing several things in the process:
  3. When the process completes successfully, it deletes the original database.
  4. Lastly, it renames the new database to the original database name.
This process does a number of things that improves the performance of your database.

First of all, the database is "defragmented", that is, it rearranges how the file is stored on the disk.  This is different than a disk defrag, but the effect is much the same: putting data into contiguous blocks.  In this process, empty space is reclaimed, usually leaving the database file size smaller.  This is the most common reason given for compacting, but perhaps not the most important.

Secondly, it rearranges the order of the records by writing them in primary key order.  This is the equivalent of a Clustered Index in other database implementation and makes the read-ahead capabilities of the database engine more efficient.

Thirdly, it rebuilds the table statistics which are used by the query optimizer to optimize queries.  It also forces a re-compile of your saved and embedded queries based on these new stastics.

Lastly, since technically it's called Compact and Repair, it will fix any page corruptions caused by hardware or network problems.

There are some limitations, however.  Since Compacting writes the database to a new file, there must be enough hard drive space to hold both databases.  You also can't compact a database is anyone else is in it.  You must have exclusive access (although it doesn't have to opened in "exclusive" mode.)  You can compact the current database (that is, the one you have open) through the Access User Interface, but not in code.  (I'll discuss that in a later post.)

So, how exactly do you compact a database?  There are several ways, both manual and programmatic, and I'll discuss that in my next post: How Do I Compact an Access Database?.

.

Monday, August 2, 2010

Access 2010: Detect and Repair

Starting with Office XP, Microsoft introduced the Detect and Repair feature for all Office applications.  This is different than the Access Compact and Repair in that it detected and repaired problems with the Office application itself (Word, Excel, Access, etc.) rather than a particular file.

In a way, it was like launching the Office Repair from Control Panel > Add/Remove Programs, except it targeted just the application you launched it from.  If launched from Word, it would repair only Word.  If launched from Excel, it would detect and repair problems in Excel only.  If...well you get the idea.

Once launched, it brings up the Detect and Repair Wizard, which looks something like this:



In Access XP and Access 2003, Detect and Repair was launched from the Help Menu.



In Access 2007, they changed it to a more comprehensive utility called Microsoft Office Diagnostics, which is launched from Office Button > Access Options > Resources Tab > Diagnose.



As far as I know, however, the option is not available in Access 2010, either from the menu system or the Ribbon.  You can, however launch it in code:

Application.CommandBars.FindControl(ID:=3774).Execute

This will launch the original Detect and Repair.
 

If you want to add it to the Ribbon, you'd have to put the code in a function in a general module:

Function Detect_Repair()
Application.CommandBars.FindControl(ID:=3774).Execute
End Function
 
Create a macro that runs the function:
 

And lastly, add the macro to a custom group on the Ribbon.
 
.

Wednesday, July 28, 2010

How do I add a value to a combo box with Not In List?

The combo box control has a nifty event called NotInList.  If the LimitToList property of my combo box is set to Yes, and I type a value that is not in the drop-down list, the NotInList event will fire.  This will allow me to capture this event and add some programming to it. 

Before I go further, I should explain that a combo box can have its drop-down list (the RowSource property) filled by a query, a field list or a value list.  The scenario I'm addressing here is a the row source filled by a query from a separate look-up table.

So suppose I have a form where I want to fill in Employee information including what Training they've had. There's a combo box on the form called cboTraining that is filled from a table called tbxTraining that lists the available training opportunities (Word, Excel, etc.).  Now suppose further that an employee takes a new type of training that is not already in the training table, say Access.  Since I have LimitToList set to Yes, I can't just type "Access" into the training field.  I have to select an item in the list.  But I also don't want my data entry person to have to stop what they're doing, open the tbxTraining table, add the value, then go back to entering data.

This is where the NotInList event comes in.  I can programmatically add the value to my tbxTraining table, refresh the combo box, and the data entry person can just continue on.

To add code to the combo's NotInList event, I open the form in design view and open the the property sheet of the combo box.  In the NotInList event, choose [Event Procedure] in the drop-down list.  The VBA editor will open with the first and last line of the subroutine already created.  Something like this:

Private Sub cboTraining_NotInList(NewData As String, Response As Integer)

End Sub

What I'm going to discuss now is the code that goes between those two lines.

There are a number of different ways to implement adding a value to the drop-down list.  Some are easier but dangerous.  Others are harder to implement, but safer.

The easiest thing for me to do is to just automatically add a new value to my lookup table when a new type of training is added to the transaction table. To do this, I would add something like the following to my NotInList event of my combo box:

Private Sub cboTraining_NotInList(NewData As String, Response As Integer)
Dim strsql As String
MsgBox "Training type does not exist. Creating new Record in Training table."
strsql = "Insert Into [tbxTraining] ([Training]) values ('" & NewData & "')"
CurrentDb.Execute strsql, dbFailOnError
Response = acDataErrAdded
End Sub

You do want to be a little careful about allowing this depending on the data entry people. It's possible to get multiples of training with slight variations. For instance, a data entry person could add "Access" or "Access Database" to the training table, both of which would refer to the same type of training. I'm not saying this shouldn't be implemented, but you do need to be careful how you do it.

A little safer is to ask the user if they want to add it. That requires only a slight variation:

Private Sub cboTraining_NotInList(NewData As String, Response As Integer)
Dim strsql As String, x As Integer
x = MsgBox("Do you want to add this value to the list?", vbYesNo)
If x = vbYes Then
strsql = "Insert Into [tbxTraining] ([Training]) values ('" & NewData & "')"
CurrentDb.Execute strsql, dbFailOnError
Response = acDataErrAdded
Else
Response = acDataErrContinue
End If
End Sub

This can still give me logical duplicates if my user isn't careful. (Sometimes they'll just say "yes" without ever thinking about it, which is just as bad as the first option).

Another way that is even safer is to programmatically open the maintenance form (say, frmTraining) when the user types a value that isn't in the list, allow them to add the record manually, then save and return to the record in the transaction form.

Private Sub cboTraining_NotInList(NewData As String, Response As Integer)
Dim strsql As String, x As Integer
x = MsgBox("Do you want to add this value to the list?", vbYesNo)
If x = vbYes Then
DoCmd.OpenForm "frmTraining"
Response = acDataErrAdded
Else
Response = acDataErrContinue
End If
End Sub

There are other variations on this theme.  On my website, I have a small sample database called NotInList.mdb which illustrates these and other options.

.

Tuesday, July 20, 2010

Access 2010: Unrecognized Database Format

I've been seeing more and more people having problems with the Unrecognized Database Format when creating or modifying an Access 2007 (accdb) format database in Access 2010 and then trying to open it again in Access 2007.

The issue appears to be that Access 2010 does not have its own file format.  When you add a feature that is specific to A2010 (like the navigation control, data macro, or calculated column), that file becomes forever unreadable to A2007, even if the new feature(s) are removed.  The solution appears to be:
  1. Remove all the new features from the file in A2010
  2. Create a new, blank accdb format database in A2010
  3. Import all the objects from the old database to the new. 
The file will then be readable by A2007.  The following link explains it more in detail: http://msdn.microsoft.com/en-us/office/cc907897.aspx.

I'm told that it is also possible to make the original file A2007 readable by removing the A2010 features and then making a minor edit to the file in a Hex editor.  But I'd be wary of that approach.  Importing the objects to a new database is safer, more reliable, and frankly simpler.

Monday, July 19, 2010

New Sample: Form_TreeView_BOM

Form_TreeView_BOM

by A.D. Tejpal

This sample db demonstrates extraction of complete hierarchical chain of sub-assemblies and components for the selected item. The user can select the desired item either by selection via combo box or by using the navigation buttons on the master subform at top left, bound to the master table T_PartMaster. Fields PartName and UnitPrice are available for user interaction (i.e. editing or new entry). UnitPrice is to be entered only for base parts (items which are not meant to have any child assemblies or components)


For the selected item, complete hierarchical chain of sub-assemblies and components gets displayed in the lower subform at right. For base parts, total quantity as well as total price are also shown in respective columns. Summary information (like maximum nesting levels, number of distinct assemblies and base parts as well as total cost of base parts needed for the selected item) gets depicted in label caption at top of this subform. For convenient analysis, the user can select any of the following styles of display, via option group below this subform:

(a) All parts (Complete hierarchical chain).

(b) Assemblies only - arranged as per relevant nesting level.

(c) Assemblies only - Straight.

(d) Base parts only - arranged as per relevant nesting level.

(e) Base parts only - Straight.

Simultaneously, the hierarchical chain of sub-assemblies and components gets depicted as tree view. Total cost of base parts (i.e. items which have no child assemblies or components) also gets depicted at bottom of tree view. Contents of tree view remain in step with the latest selection (out of five listed above) in option group.

Also, there is two way synchronization between tree view and the lower subform at right. If the user selects any node in tree view, corresponding record in subform becomes the current record. Conversely, if the user navigates to any record in the subform, corresponding node in tree view assumes selected state. PartID of matching record in the subform gets highlighted in a manner similar to the shade signifying selected node in treeview.

As the user navigates through master subform at top left, the contents of tree view as well as the two subforms at right keep getting updated as per current selection (treating current PartID on master subform as the top item for which hierarchical chain is to be extracted).

You can find the sample here: http://www.rogersaccesslibrary.com/forum/topic545_post557.html#557

.