Archive for June, 2010

June 10th, 2010

MS Access – Select a Printer

Open the Print Dialog

If all you want is to open the print dialog using code then the following tidbit of code is all you need.

docmd.RunCommand acCmdPrint

Be sure to trap error number 2501 in case the user decides to cancel the action.

Code which printer is used in VBA

On the other hand, if you are looking to hard code which printer is used to print a document then the following is addressed to you.

The following information come from Albert D. Kallal (Access MVP)

In access 2002 and later, there is a built in printer object, and it lets you switch the printer with ease.

You can use:

Set Application.Printer = Application.Printers("HP LaserJet Series II")

So, to save/switch, you can use:

Dim strDefaultPrinter  as string
 
' get current default printer.
strDefaultPrinter = Application.Printer.DeviceName
 
' switch to printer of your choice:
Set Application.Printer = Application.Printers("HP LaserJet Series II")
 
'do whatever....print reports

'Swtich back.
Set Application.Printer = Application.Printers(strDefaultPrinter)

If you are using a earlier versions, then you can use my lightweight printer switch code here:

http://www.members.shaw.ca/AlbertKallal/msaccess/msaccess.htm

So, I do often build a form that displays a list of installed printers, and allow the user to select a printer. The above code example has such a form, but that old example is REALLY only of use for pre-a2002 applications.

So, for special forms, or things like invoice printer, I sill do NOT save which printer with the report (you *can* save the printer in ms-access, but the feature is not much use for users since if they install, or purchase a new printer..then the name changes..and your application will complain). So, while we do switch printers in code..we STILL avoid saving the particular printer to a given report. So, we always still set reports to use the default printer.

Since the margins, and portrait/landscape are saved with the report, then generally, just switching printers should do the trick if we kept the margins fairly large in the reports.”

Allen Browne also has a good utility for this purpose. More details can be found at http://allenbrowne.com/AppPrintMgt.html.

June 10th, 2010

MS Access – Error 2501

Error 2501 which states:

The | action was canceled. You used a method of the DoCmd object to carry out an action in Visual Basic, but then clicked Cancel in a dialog box. For example, you used the Close method to close a changed form, then clicked Cancel in the dialog box that asks if you want to save the changes you made to the form.

is a very illusive error. It can mean a number of things which make it that more difficult to properly troubleshoot.

This said at one of my client’s, and after much troubleshooting of the database code, it was determined that the issue did not lie with the database per se, but rather with the permission that the user had on the assigned default printer. The fact that the user did not sufficient priviledges to use the assigned default printer caused access to not be able to preview, little alone print, the document and instead generated the Error 2501.

So next time you get and Error 2501 trying to open a report that previously worked, or cannot find any problems with, consider validating the user’s priviledges on their default printer.

June 10th, 2010

MS Access VBA – Determine if a Form is Open

The following simple little procedure can be used to check if a given form is already open.

'---------------------------------------------------------------------------------------
' Procedure : IsFrmOpen
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Determine whether a form is open or not
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFrmName  : Name of the form to check if it is open or not
'
' Usage Example:
' ~~~~~~~~~~~~~~~~
' IsFrmOpen("Form1")
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2010-May-26                 Initial Release
'---------------------------------------------------------------------------------------
Function IsFrmOpen(sFrmName As String) As Boolean
On Error GoTo Error_Handler
 
    If Application.CurrentProject.AllForms(sFrmName).IsLoaded = True Then
        IsFrmOpen = True
    Else
        IsFrmOpen = False
    End If
 
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: IsFrmOpen" & vbCrLf & "Error Description: " & _
    Err.Description, vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

June 10th, 2010

MS Access VBA – Count the Number of Open Forms

The following function will return the number of currently open forms.

'---------------------------------------------------------------------------------------
' Procedure : CountOpenFrms
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Returns a count of the number of loaded Forms (preview or design)
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites.
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2009-Oct-30                 Initial Release
'---------------------------------------------------------------------------------------
Function CountOpenFrms()
On Error GoTo Error_Handler
 
    CountOpenFrms = Application.Forms.Count
 
Exit Function
 
Error_Handler:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: CountOpenFrms" & vbCrLf & "Error Description: " & _
    Err.Description, vbCritical, "An Error has Occured!"
    Exit Function
End Function

June 10th, 2010

MS Access VBA – List Currently Open Forms

You can use the following function to retrieve a listing of all the currently open forms.

'---------------------------------------------------------------------------------------
' Procedure : ListOpenFrms
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Returns a list of all the loaded forms (preview or design)
'             separated by ; (ie: Form1;Form2;Form3)
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites.
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2009-Oct-31                 Initial Release
'---------------------------------------------------------------------------------------
Function ListOpenFrms()
On Error GoTo Error_Handler
 
    Dim DbF     As Form
    Dim DbO     As Object
    Dim Frms   As Variant
 
    Set DbO = Application.Forms 'Collection of all the open forms
    
    For Each DbF In DbO    'Loop all the forms
            Frms = Frms & ";" & DbF.Name
    Next DbF
 
    If Len(Frms) > 0 Then
        Frms = Right(Frms, Len(Frms) - 1)   'Truncate initial ;
    End If
 
    ListOpenFrms = Frms
 
Exit Function
 
Error_Handler:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: ListOpenFrms" & vbCrLf & "Error Description: " & _
    Err.Description, vbCritical, "An Error has Occured!"
    Exit Function
End Function

June 10th, 2010

MS Access – Password Protect a Form

There are a multitude of methods to password protect a form access to users should you not wish to implement Access’ built-in User-Level Security. The following Microsoft Knowledge Base article illustrates how you can achieve exactly this.

How to Create a Password Protected Form or Report

June 10th, 2010

MS Access – Limit the Number of Records Input in a Form

Have you ever wanted to limit the number of records that could be input into a table through a form? Simply input the following Form Current Event!

Private Sub Form_Current()
    Dim intMaxNumRecs as Integer
 
    intMaxNumRecs = 5 'Max Number of Records to Allow

    If Me.NewRecord Then
        With Me.RecordsetClone
            If .RecordCount > 0 Then
                .MoveLast:  .MoveFirst
                If .RecordCount >=  intMaxNumRecs Then
                    MsgBox "Can't add more than " &  intMaxNumRecs & " records in the demo database!"
                    .MoveLast
                    Me.Bookmark = .Bookmark
                End If
            End If
        End With
    End If
End Sub

June 10th, 2010

MS Access – Color Picker

Depending on your needs, it can also be useful to have a color picker on your form. To this end check out

Calling Windows Choose Color Dialog
Leban’s Font and Color Dialog

June 10th, 2010

MS Access – Calculator Control

Another common need for a good number of application is a simple pop-up calculator. To my surprise, MS Access still does not come with any form of a calculator. No need to worry though! There are a great number of such MS Access calculators available for free online. Below are three examples of free calculators you can simply download and drop into your database application.

http://www.datastrat.com/Download/popCalc.zip
http://www.byerley.net/Access2kCalcDemo.zip
http://www.mvps.org/access/downloads/calc.zip

If you aren’t satisfied with those MS Access calculators listed above, why not create your own. Use the following link to learn how.

How to Build an MS Access Calculator

June 10th, 2010

MS Access – Calendar Control

A very common issue with any documents, not only access databases, is how data is entered by the users, most notably date entries. To ensure proper data entry it is very useful to give your users simple graphical tools and elimate keyboard entry. To this aim, the following are 2 excellent date pickers that can very easily be incorporated into any of your database applications.

Allen Browne’s Popup Calendar a very basic calendar easy to setup and use. This is a form based calendar.
Stephen Lebans Calendar a more advanced calendar (more options) equally easy to setup and use. This is an API based calendar.
Arvin Meyer’s Calendar another basic form based calendar which is easy to implement in any database.

It is also very important to note that whenever possible you should always avoid the use of ActiveX controls as they can lead to reference and versioning issues. The calendars listed above will not suffer from such issues.

Also, if you have develop an mdb application working in 2007 and have taken advantage of the pop-calendar included in Access 2007. If you wish you database to be backwards compatible then you must implement your own calendar, as earlier version do not have this functionality!

June 10th, 2010

MS Access Queries – Using Built-in Functions in Queries

For new user a quick word of caution to try and avoid one potential headache when using built-in functions within a query.

For instance:
Let say you with to use an update query to standardize the text in a field so that it is ‘Proper Cased’ (ie: capitalize the first character of each word – Good for Names, Address Info,… ), you would use the StrConv() function.

Now in vba you would do something like:
StrConv(“joHn HOLMEs”, vbProperCase)

However, if you were to use the same in the QBE when building your query for a field named “client_name”, you would see that Access would automatically place the vbProperCase between quotes, like:
StrConv([client_name], “vbProperCase”)
and if you ran your update query like this, you would end up with blanked fields. Yes, you would actually lose your data. I know, because I once made the mistake.

So what is the solution? It is quite simple actually! The QBE does not seem to have access to the built-in vba constant values. As such, instead of using the built-in vba constant values, you need to replace them by their literal values. In this case, 3. So our code would become:
StrConv([client_name], 3)

June 10th, 2010

MS Access VBA – Create a Query

The following function can be use VBA to create a query on the fly.

'---------------------------------------------------------------------------------------
' Procedure : CreateQry
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Create a new query in the current database
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sQryName - Name of the query to create
' sSQL - SQL to use
'
' Usage Example:
' ~~~~~~~~~~~~~~~~
' CreateQry "qry_ClientList", "SELECT * FROM Clients ORDER BY ClientName"
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2009-Nov-07                 Initial Release
'---------------------------------------------------------------------------------------
Sub CreateQry(sQryName As String, sSQL As String)
On Error Resume Next
    Dim db          As DAO.Database
    Dim qdf         As DAO.QueryDef
 
    Set db = CurrentDb
 
    With db
        'In the next line we try and delete the query
        'If it exist it will be deleted, otherwise it will raise an error but since
        'we set our error handler to resume next it will skip over it and continue
        'with the creation of the query.
        .QueryDefs.Delete (sQryName)    'Delete the query if it exists
On Error GoTo Error_Handler             'Reinitiate our standard error handler
        Set qdf = .CreateQueryDef(sQryName, sSQL)    'Create the query
    End With
 
    db.QueryDefs.Refresh  'Refresh the query list to display the newly created query

Error_Handler_Exit:
    On Error Resume Next
    Set qdf = Nothing
    Set db = Nothing
    Exit Sub
 
Error_Handler:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: CreateQry" & vbCrLf & "Error Description: " & _
    Err.Description, vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Sub
June 10th, 2010

MS Access VBA – Edit a Query’s SQL Statement

Have you ever needed to change/alter/update/redefine a query’s underlying SQL statement using VBA? It really isn’t very hard. Below is a simple function which illustrates exactly how to achieve this!

'---------------------------------------------------------------------------------------
' Procedure : RedefQry
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Redefine a query's SQL using VBA
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sQryName  : Name of the query to redefine the SQL of
' sSQL      : New SQL statement to use to define the query
'
' Usage Example:
' ~~~~~~~~~~~~~~~~
' ? RedefQry("qry_ClientList","SELECT * FROM Clients ORDER BY ClientName")
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2009-Nov-07                 Initial Release
'---------------------------------------------------------------------------------------
Sub RedefQry(sQryName As String, sSQL As String)
On Error GoTo Error_Handler
    Dim qdf         As DAO.QueryDef
 
    Set qdf = CurrentDb.QueryDefs(sQryName)
    qdf.SQL = sSQL  'Redefine the Query's SQL

Error_Handler_Exit:
    On Error Resume Next
    Set qdf = Nothing
    Exit Sub
 
Error_Handler:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: RedefQry" & vbCrLf & "Error Description: " & _
    Err.Description, vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Sub
June 10th, 2010

MS Access VBA – Determine if a Query Exists

The following procedure checks to see if a query exists in the current database.

'---------------------------------------------------------------------------------------
' Procedure : DoesQryExist
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Determine if the specified query exists or not in the current database
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sQueryName: Name of the query to check the existance of
'
' Usage Example:
' ~~~~~~~~~~~~~~~~
' DoesQryExist("Query1")
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2010-Feb-02             Initial Release
'---------------------------------------------------------------------------------------
Function DoesQryExist(sQueryName As String) As Boolean
   Dim db   As DAO.Database
   Dim qdf  As QueryDef
 
On Error GoTo Error_Handler
   'Initialize our variable
   DoesQryExist = False
 
   Set db = CurrentDb()
   Set qdf = db.QueryDefs(sQueryName)
 
   DoesQryExist = True  'If we made it to here without triggering an error
                        'the query exists

Error_Handler_Exit:
   On Error Resume Next
   Set qdf = Nothing
   Set db = Nothing
   Exit Function
 
Error_Handler:
   If Err.Number = 3265 Then
      'If we are here it is because the query could not be found
   Else
      MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
      Err.Number & vbCrLf & "Error Source: DoesQryExist" & vbCrLf & "Error Description: " & _
      Err.Description, vbCritical, "An Error has Occured!"
   End If
   Resume Error_Handler_Exit
End Function

Another alternate method to using this function would be to loop through all the QueryDefs to see if the specified name matched any query in the list, but I believe this above listed function is better.

June 10th, 2010

MS Access VBA – List Query Fields

The following function will return a listing of all the fields/columns that are shown in a query.

'---------------------------------------------------------------------------------------
' Procedure : listQueryFields
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Return a listing of all the fields (column names) of a give Query
' Copyright : The following code may be used as you please, but may not be resold, as
'             long as the header (Author, Website & Copyright) remains with the code.
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' strQryName - Name of the query to list the fields of.
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2007-June-01            Initial Release
'---------------------------------------------------------------------------------------
Function listQueryFields(strQryName As String) As String
On Error GoTo listQueryFields_Error
    Dim db As DAO.Database
    Dim qryfld As DAO.QueryDef
    Dim fld As Field
 
    Set db = CurrentDb()
    Set qryfld = db.QueryDefs(strQryName)
    For Each fld In qryfld.Fields    'loop through all the fields of the Query
        Debug.Print fld.Name
    Next
 
Error_Handler_Exit:   
    Set qryfld = Nothing
    Set db = Nothing
    Exit Function
 
listQueryFields_Error:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: listQueryFields" & vbCrLf & _
    "Error Description: " & Err.Description, vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function
June 10th, 2010

MS Access VBA – List of Database Queries

The following VBA Function can be used to produce a list of all the queries within a given MS Access database.

'---------------------------------------------------------------------------------------
' Procedure : ListDbQrys
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Returns a ';' separated string containing the names of all the queries
'             within the database (use Split() to convert the string to an array)
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2007-Nov                Initial Release
'---------------------------------------------------------------------------------------
Function ListDbQrys() As String
On Error GoTo Error_Handler
 
    Dim DbO     As AccessObject
    Dim DbCD     As Object
    Dim Qrys    As String
 
    Set DbCD = Application.CurrentData
 
    For Each DbO In DbCD.AllQueries
        Qrys = Qrys & ";" & DbO.Name
    Next DbO
    Qrys = Right(Qrys, Len(Qrys) - 1) 'Truncate initial ;

    ListDbQrys = Qrys
 
Error_Handler_Exit:
    Set DbCD = Nothing
    Set DbO = Nothing 
    Exit Function
 
Error_Handler:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: ListDbQrys" & vbCrLf & "Error Description: " & _
    Err.Description, vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function
June 10th, 2010

MS Access – List of Database Queries

The following SQL statement can be used to produce a list of all the queries within a given MS Access database.

SELECT MsysObjects.Name AS [List OF Queries]
FROM MsysObjects
WHERE (((MsysObjects.Name) NOT LIKE "~*" AND (MsysObjects.Name) NOT LIKE "MSys*") AND ((MsysObjects.TYPE)=5))
ORDER BY MsysObjects.Name;
June 10th, 2010

MS Access VBA – Determine if a Field Exists in a Table

Ever needed a way to determine if a table contained a specific field? The following procedure permits you to check exactly that.

'---------------------------------------------------------------------------------------
' Procedure : DoesTblFieldExist
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Determine if a field exists with the specified table
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sTableName: Name of the table to check the existance of the field in
' sFieldName: Name of the field to check the existance of
'
' Usage Example:
' ~~~~~~~~~~~~~~~~
' DoesTblFieldExist("Table1","Field1")
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2010-Feb-02             Initial Release
'---------------------------------------------------------------------------------------
Function DoesTblFieldExist(sTableName As String, sFieldName As String) As Boolean
   Dim db            As DAO.Database
   Dim tdf           As TableDef
   Dim I             As String
   Dim bTableExists  As Boolean
 
On Error GoTo Error_Handler
   'Initialize our variables
   DoesTblFieldExist = False
   bTableExists = False
 
   Set db = CurrentDb()
   Set tdf = db.TableDefs(sTableName)
 
   bTableExists = True  'If we made it to here without triggering an error
                        'the table exists
  
   I = tdf.Fields(sFieldName).Name
 
   DoesTblFieldExist = True   'If we made it to here without triggering an
                              'error the table field exists

Error_Handler_Exit:
   On Error Resume Next
   Set tdf = Nothing
   Set db = Nothing
   Exit Function
 
Error_Handler:
   If Err.Number = 3265 And bTableExists = False Then
      'Table not found in the current database
      MsgBox "The specified Table could not be found in the current database", vbCritical
   ElseIf Err.Number = 3265 And bTableExists = True Then
      'Field not found in the specified table
     
   Else
      MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
      Err.Number & vbCrLf & "Error Source: DoesTblFieldExist" & vbCrLf & "Error Description: " & _
      Err.Description, vbCritical, "An Error has Occured!"
   End If
   Resume Error_Handler_Exit
End Function
June 10th, 2010

MS Access VBA – Determine if a Table Exists

A simple procedure to test for the existance of a table in the current database.

'---------------------------------------------------------------------------------------
' Procedure : DoesTblExist
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Determine if the specified table exists or not in the current database
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sTableName: Name of the table to check the existance of
'
' Usage Example:
' ~~~~~~~~~~~~~~~~
' DoesTblExist("Table1")
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2010-Feb-02             Initial Release
'---------------------------------------------------------------------------------------
Function DoesTblExist(sTableName As String) As Boolean
   Dim db   As DAO.Database
   Dim tdf  As TableDef
 
On Error GoTo Error_Handler
   'Initialize our variable
   DoesTblExist = False
 
   Set db = CurrentDb()
   Set tdf = db.TableDefs(sTableName)
 
   DoesTblExist = True  'If we made it to here without triggering an error
                        'the table exists

Error_Handler_Exit:
   On Error Resume Next
   Set tdf = Nothing
   Set db = Nothing
   Exit Function
 
Error_Handler:
   If Err.Number = 3265 Then
      'If we are here it is because the table could not be found
   Else
      MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
      Err.Number & vbCrLf & "Error Source: DoesTblExist" & vbCrLf & "Error Description: " & _
      Err.Description, vbCritical, "An Error has Occured!"
   End If
   Resume Error_Handler_Exit
End Function

Another alternate approach is to simply try to utilize the table using code and if it returns an error you know the table does not exist. Both approaches are valid and usage depends on your needs.

June 10th, 2010

MS Access VBA – Import External Database Tables

The following procedure will import all the non-system tables from the specified database into the current database.

'---------------------------------------------------------------------------------------
' Procedure : ImportAllTbls
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Import all the tables from an external Access database
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sExtDbPath - Full Path & Filename of the Database to import the tables from
'
' Usage Example:
' ~~~~~~~~~~~~~~~~
' ImportAllTbls "C:\Databases\development01.mdb"
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2009-Jan-07                 Initial Release
'---------------------------------------------------------------------------------------
Sub ImportAllTbls(sExtDbPath As String)
On Error GoTo Error_Handler
    Dim db      As DAO.Database
    Dim tdf     As DAO.TableDef
 
    Set db = OpenDatabase(sExtDbPath)
 
    For Each tdf In db.TableDefs 'Loop through all the table in the external database
        If Left(tdf.Name, 4) <> "MSys" Then 'Exclude System Tables
            On Error Resume Next
            Access.DoCmd.TransferDatabase acImport, "Microsoft Access", sExtDbPath, _
                                          acTable, tdf.Name, tdf.Name, False
        End If
    Next tdf
    db.Close
 
    Set db = Nothing 'Cleanup after ourselves

Exit Sub
 
Error_Handler:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: ImportAllTbls" & vbCrLf & "Error Description: " & _
    Err.Description, vbCritical, "An Error has Occured!"
    Exit Sub
End Sub
June 10th, 2010

MS Access VBA – Determine which Make-Table Query Created a Table

'---------------------------------------------------------------------------------------
' Procedure : findmaketbl
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Locate which Make-Table Query is creating a table
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sTableName    Name of the Table that you believe is created by a Make-Table Query.
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
'
**************************************************************************************
' 1         2009-Jun-12                 Initial Release
'---------------------------------------------------------------------------------------
Function findmaketbl(sTableName As String)
On Error GoTo Error_Handler
 
    Dim db      As DAO.Database
    Dim qdf     As DAO.QueryDef
    Dim sSQL    As String
 
    Set db = CurrentDb
 
    For Each qdf In db.QueryDefs
        'qdf.Name    'The current query's name
        'qdf.SQL     'The current query's SQL statement
        sSQL = qdf.SQL
        If InStr(sSQL, " INTO ") And InStr(sSQL, sTableName) Then
            'The Query is a Make Table Query and has our TableName we are looking for
            MsgBox "Query:'" & qdf.Name & "' is a Make-Table Query for Table '" & _
                    sTableName & "'.", vbInformation
        End If
    Next
 
    Set qdf = Nothing
    Set db = Nothing
 
If Err.Number = 0 Then Exit Function
 
Error_Handler:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: findmaketbl" & vbCrLf & "Error Description: " & _
    Err.Description, vbCritical, "An Error has Occured!"
    Exit Function
End Function
June 10th, 2010

MS Access VBA – Determine if a Value is in a Table

'---------------------------------------------------------------------------------------
' Procedure : ValInTbl
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Verifies if a value is found in a table
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sTable    : Name of the table to search for the specified value
' sField    : Name of the field in the specified table to search for the specified value
' sValue    : Value to search for
'
' Usage:
'~~~~~~~
' ValInTbl("tbl_Units", "UnitNo", 54201)
' ValInTbl("tbl_Employees", "FirstName", "Daniel")
' ValInTbl("tbl_Followup", "AttendInitSession", True)
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2009-Mar-14             Initial Release
' 2         2010-Oct-13             Adjust the sSQL string based on the table field type
'---------------------------------------------------------------------------------------
Function ValInTbl(sTable As String, sField As String, sValue As String) As Boolean
On Error GoTo Error_Handler
    Dim db      As DAO.Database
    Dim rs      As DAO.Recordset
    Dim sSQL    As String
 
    Set db = CurrentDb()
    Select Case db.TableDefs(sTable).Fields(sField).Type
        Case dbByte, dbInteger, dbLong, dbSingle, dbDouble, dbBoolean
            sSQL = "SELECT [" & sField & "] FROM [" & sTable & "] WHERE [" & sField & "]=" & sValue
        Case dbText, dbMemo
            sSQL = "SELECT [" & sField & "] FROM [" & sTable & "] WHERE [" & sField & "]='" & sValue & "'"
        Case dbDate
            sSQL = "SELECT [" & sField & "] FROM [" & sTable & "] WHERE [" & sField & "]=#" & sValue & "#"
    End Select
    Set rs = db.OpenRecordset(sSQL, dbOpenSnapshot)
 
    If rs.RecordCount <> 0 Then
        ValInTbl = True
    Else
        ValInTbl = False
    End If
 
Error_Handler_Exit:
    On Error Resume Next
    rs.Close
    Set rs = Nothing
    Set db = Nothing
    Exit Function
 
Error_Handler:
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: ValInTbl" & vbCrLf & _
           "Error Description: " & Err.Description, _
           vbCritical, "An Error has Occured!"
    Resume Error_Handler_Exit
End Function

June 10th, 2010

MS Access VBA – Wipe all the Tables in the Database

'---------------------------------------------------------------------------------------
' Procedure : WipeTables
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Empty all the tables in a db of all data (wipe the db clean (does not
'             include system tables)
' Copyright : The following code may be used as you please, but may not be resold, as
'             long as the header (Author, Website & Copyright) remains with the code.
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2008-Feb                Initial Release
'---------------------------------------------------------------------------------------
Function WipeTables() As String
On Error GoTo WipeTables_Error
    Dim db As DAO.Database
    Dim td As DAO.TableDefs
 
    Set db = CurrentDb()
    Set td = db.TableDefs
    DoCmd.SetWarnings False 'Turn off confirmation prompt to user
   
    For Each t In td    'loop through all the fields of the tables
        If Left(t.Name, 4) = "MSys" Or Left(t.Name, 1) = "~" Then GoTo Continue
        DoCmd.RunSQL ("DELETE [" & t.Name & "].* FROM [" & t.Name & "];")
Continue:
    Next
 
    DoCmd.SetWarnings True  'Turn back on confirmation prompt to user
    Set td = Nothing
    Set db = Nothing
    WipeTables = True
 
If Err.Number = 0 Then Exit Function
 
WipeTables_Error:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: WipeTables" & vbCrLf & _
    "Error Description: " & Err.Description, vbCritical, "An Error has Occured! "
    Exit Function
End Function
June 10th, 2010

MS Access VBA – Delete All Table Records

'---------------------------------------------------------------------------------------
' Procedure : WipeTable
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Empty all the data of the specified table
' Copyright : The following code may be used as you please, but may not be resold, as
'             long as the header (Author, Website & Copyright) remains with the code.
'
' Imput variables:
' ---------------
' strTblName: Name of the table to delete all the records in.
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2008-Feb                Initial Release
'---------------------------------------------------------------------------------------
Function WipeTable(strTblName As String) As String
On Error GoTo WipeTable_Error
 
    DoCmd.SetWarnings False 'Turn off confirmation prompt to user
   
    DoCmd.RunSQL ("DELETE [" & strTblName & "].* FROM [" & strTblName & "];")
 
    DoCmd.SetWarnings True  'Turn back on confirmation prompt to user

    WipeTable = True
 
If Err.Number = 0 Then Exit Function
 
WipeTable_Error:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: WipeTable" & vbCrLf & _
    "Error Description: " & Err.Description, vbCritical, "An Error has Occured! "
    Exit Function
End Function
June 10th, 2010

MS Access VBA – List the Tables in a Database

'---------------------------------------------------------------------------------------
' Procedure : listTables
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Return a listing of all the tables in the database
' Copyright : The following code may be used as you please, but may not be resold, as
'             long as the header (Author, Website & Copyright) remains with the code.
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' bShowSys - True/False whether or not to include system tables in the list
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2008-June-01            Initial Release
'---------------------------------------------------------------------------------------
Function listTables(bShowSys As Boolean) As String
On Error GoTo listTables_Error
    Dim db As DAO.Database
    Dim td As DAO.TableDefs
 
    Set db = CurrentDb()
    Set td = db.TableDefs
    For Each t In td    'loop through all the fields of the tables
        If Left(t.Name, 4) = "MSys" And bShowSys = False Then GoTo Continue
        Debug.Print t.Name
        'CurrentDb().OpenRecordset ("DELETE * FROM " & t.Name)
Continue:
    Next
 
    Set td = Nothing
    Set db = Nothing
If Err.Number = 0 Then Exit Function
 
listTables_Error:
    MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
    Err.Number & vbCrLf & "Error Source: listTable" & vbCrLf & _
    "Error Description: " & Err.Description, vbCritical, "An Error has Occured!"
    Exit Function
End Function