Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

No Data and Report Error

Introduction.

Report Source Query or Table can end up with no output records. In that case, some of the controls with the formula in the Report will show #Error. An image of a sample report is given below:

The #Error message at the top-right corner appears because the control contains a formula intended to display the reporting period. Similarly, the controls to the right of the word TOTAL—which display subtotals, totals, and detail line values—also show errors. This occurs when the report’s underlying query returns no records for the period selected by the user.

Although this is not a critical issue, it is considered poor practice to present or archive such a report with visible errors, especially if it needs to be shared as a NIL REPORT or retained for audit or future reference.

The modified version of the report shown below resolves this issue. It includes a clear comment, displays zero values in the summary controls, and correctly prints the reporting period.

I have made a few modifications to the Report Design to add a hidden label at the footer of the Report with the Caption: *** Congratulations *** Nothing Pending to show up when there are no output Records for the Report. The Visible Property of the label is set to No manually. In the Detail Section under the Description Column, it shows *** NIL REPORT ***. The period for which the Report is prepared is also shown to the right, above the Detail Section headings.

The Report Period (DateFrom and DateTo) is normally entered into a Parameter Table and joined with the Report Source Table in a Query to use them for criteria and for displaying on the Report.


Few Changes in the Report

Created two Text Controls (with the names From and To, respectively) at the Report Header Section to the right of the Control name STAFFNAME to load the DateFrom and DateTo Values from the Report Parameter Table with the DLookup() Function:

=DLookUp("DateFrom","Report_Param")

Second Control has the expression to read DateTo from the Report_Param Table, and both values are used in the expression (=" Period: " & [frm] & " To " & [To]) to format the values to show the output as in the second image given above. These are all the cosmetic changes required in the Report.

Temporary Table for Report.

The major change is creating a temporary table with a single blank record, which should have the same structure as the Source Table or Query, and attaching it to the Report. If your Report is using a Table as Report Source Data, then make a copy of the structure of the Table and add a tmp_ prefix to the table name, like tmp_myReport. If it is a Query, then create a Make-Table Query using the Report Source Query and create a temporary table. Add a blank record in the temporary table. If your Report Table has a Text Field that is displaying the value on the Report, then type *** NIL REPORT *** in that field. Fill numeric fields with 0 and keep all other fields Empty.

How the Trick Works

The trick is that when the Report is opened by the User, we will check whether the original Report Source Table or Query has any records in it or not. If not, swap the Temporary Table with the Report Source Table or Query. The hidden Label's Visible Property will be set to Yes to display the comment *** CONGRATULATIONS *** NOTHING PENDING. Since the temporary table has a single blank record, the Summary Controls will not show errors.

We need a few lines of VBA Code in the Report_Open() Event Procedure to check and swap the Report Source Table or Query.

Few Lines of VBA Code

Private Sub Report_Open(Cancel As Integer)
Dim i As Integer
i = DCount("*", "myReport")
If i = 0 Then
   Me.RecordSource = "tmp_MyReport"
   Me.lblMsg.Visible = True
End If
End Sub

Copy the above lines of code in the Report's VBA Module and make changes to insert the correct Table/Query and tmp_myReport names.

Share:

Lost Links of External Tables

Introduction.

We have already learned several methods to work with external data sources. Linking them to an MS-Access Database or directly opening them in Queries by setting Source Database and SourceConnectStr Properties. In either case, the Source Data must be present in its original location at all times.

However, there is always a possibility that the links to some of these tables may be lost—for instance, if a source table is accidentally deleted or renamed. Such issues typically go unnoticed until we attempt to work with the linked tables, often resulting in errors that may appear unexpectedly.

To alleviate this problem, run a check on the linked tables as soon as the Database is open for normal operations. If any of the linked Tables are not in place, then warn the User about it and shut down the Application if it has serious implications.

How do we determine whether a linked external table has lost its connection with the Database or not? It is easy to attempt to open the linked table, and if it ends up in errors, you can be sure the table link is missing. 

There may be several tables in a database, local tables or linked ones. How can we single out the linked ones alone and open them to check the status? Again, this is not a serious issue, and you already have the answer if you have gone through the earlier Articles explaining several methods of accessing external data and usage of Connection Properties of Linked Tables and Queries.

The Connection Property Value

We need a small VBA routine to iterate through the Table definitions and check the Connect Property value, and if it is set with a Connect String, then it is a linked table; otherwise, it is a local table. When we encounter a linked table, we will attempt to open it to read data. If this process triggers an Error, then we will prepare a list of such cases and display it at the end to inform the User so that she can initiate appropriate remedial action to rectify the error.

A sample VBA routine is given below. Copy and paste the program into a Global Module and save it.

Public Function LostLinks()
'----------------------------------------------------
'Author : a.p.r. pillai
'URL    : www.msaccesstips.com
'Date   : 21/09/2008
'----------------------------------------------------
Dim msg As String, tbldef As TableDef
Dim strConnect As String, cdb As Database
Dim rst As Recordset, strTableName As String
Dim strDatabase As String, loc As Integer
Dim loc2 As Integer

On Error Resume Next

Set cdb = CurrentDb
For Each tbldef In cdb.TableDefs
    strConnect = tbldef.Connect

    If Len(strConnect) > 0 Then
       strTableName = tbldef.NAME
       Set rst = cdb.OpenRecordset(strTableName, dbOpenDynaset)
       If Err > 0 Then
          If Len(msg) = 0 Then
             msg = "The following Linked Tables are missing:" & vbCr & vbCr
          End If
          msg = msg & strTableName & vbCr
          Err.Clear
        End If
        rst.Close
    End If
Next

If Len(msg) > 0 Then
    MsgBox msg, , "LostLinks()"
End If

End Function

Call the Routine from an Autoexec Macro or from the Form_Load() Event Procedure of the Application's Startup or Main Screen.

Earlier Post Link References:

Share:

Link External Tables with VBA

Introduction.

We all know how to link to a table from external data sources manually.

  1. Highlight Get External Data from the File Menu.

  2. Select Link Tables from the displayed options.

  3. Select the file type: dBase, Excel, etc., in the Files of Type control.

  4. Track the location of the file and select it.

  5. Click the link to attach the selected table to the Current Database.

If you are linking an external table from a Network Location, use the UNC (Universal Naming Conventions) type location reference (like \\hosfs03\accounts\myDatabase\...), rather than using a mapped drive location reference like H:\MyDatabase

You can even use your Local Drive's share name in this manner. 

\\yourPCName\C$\Databases\myDatabase.mdb

This method ensures that even if the drive mapping changes—for example, from **H:\** to **K:\** or any other letter—MS Access can still locate the linked tables without any issues. Otherwise, you would need to manually update the table locations using **Tools → Database Utilities → Linked Table Manager** to refresh the changed path references.

We have already seen that we can work with external tables without linking them permanently to the current database.

Here, we will link external Tables using VBA to the Current Database. After linking the table, we will print the contents of five records into the Debug Window and delete the link.

The Steps to follow

We will go through the following steps to link a Table to a Database with VBA:

  1. Create a temporary Table Definition (Tabledef) without any Field Definitions in the Current Database.

  2. Load the Connect Property of tabledef. with Connection String Value

  3. Link the external Table to the temporary Table definition (Tabledef)

  4. Add the temporary Table definition to the Tabledefs Group.

  5. Rename the temporary Table to match the Source Table Name.

The VBA Functions.

We will write two VBA Functions for our examples. Copy and paste the following VBA code into a Global Module of your MS-Access Database and save it:

Public Function LinkMain()
Dim strConnection As String
Dim sourceTable As String

strConnection = ";DATABASE=D:\Program Files\Microsoft office\Office\Samples\Northwind.mdb;TABLE=Orders"

sourceTable = "Orders" 'Access Table Name

LinkExternal strConnection, sourceTable

End Function
Function LinkExternal(ByVal conString As String, sourceTable As String)
Dim db As Database, i As Integer, j As Integer
Dim linktbldef As TableDef, rst As Recordset

Set db = CurrentDb
Set linktbldef = db.CreateTableDef("tmptable") 'create temporary table definition

linktbldef.Connect = conString 'set the connection string
linktbldef.SourceTableName = sourceTable 'attach the source table
db.TableDefs.Append linktbldef 'add the table definition to the group
db.TableDefs.Refresh 'refresh the tabledefinitions

linktbldef.NAME = sourceTable 'rename the tmptable to original source table name

'open the recordset and print 5 records in the debug window
Set rst = db.OpenRecordset(sourceTable, dbOpenDynaset)
i = 0
Do While i < 5 And Not rst.EOF
  For j = 0 To rst.Fields.Count - 1
     Debug.Print rst.Fields(j).Value,
  Next: Debug.Print
  rst.MoveNext
  i = i + 1
Loop
rst.Close

db.TableDefs.Delete sourceTable 'remove to stay the table linked
db.Close
Set rst = Nothing
Set linktbldef = Nothing
Set db = Nothing

End Function

How it works.

The first program, LinkMain(), calls the LinkExternal() Sub Routine with strConnection and SourceTable name as parameters. Northwind.mdb sample database and Orders Table are passed as parameters. Open the Debug Window (Immediate Window) by pressing Ctrl+G. Click anywhere within the LinkMain() program and press F5 to run the code and print five records of the Orders table from the Northwind.mdb database.

The LinkExternal() Program performs the five steps of action explained above.

Replace the strConnection and sourceTable with the following sample values for opening a dBase Table:

strConnection = "dBase IV;HDR=NO;IMEX=2;DATABASE=D:\msaccesstips" sourceTable = "Branches" 'Access Table Name

Tip: If you don't have a dBase Table to try the Code, then export a Table from MS-Access into the dBase format and run the Code with changes.

Change the Database Folder name and the Table name with your own dBase Folder and Table names.

For Excel-based Tables, two methods are given below.

  1. Uses Worksheet Reference (Sheet1$) as the source Table location. The $ symbol is necessary with the Worksheet name.:

    strConnection = "Excel 5.0;HDR=YES;IMEX=2;DATABASE=D:\msaccesstips\Branch.xls" sourceTable = "Sheet1$" 'Excel Sheet Name Reference
    

    The topmost row contents of the table area will be used as Field Names.

    strConnection = "Excel 5.0;HDR=YES;IMEX=2;DATABASE=D:\msaccesstips\Branch.xls" sourceTable = "BranchNames" 'Excel Range Name Reference
    
  2. Excel Range Name, Branch Names will be used as the Table location. The first line is the same as above for this example, also.

Earlier Post Link References:

Share:

Source Connect Str Property and ODBC

Introduction.

We have already seen that the SourceConnectStr property, when used together with the 'Source Database' property in an MS Access Query, allows us to open and work directly with external data sources such as dBase, FoxPro (Versions 2.5 or 3.0), and Excel tables.

We also learned how to include these property specifications within an 'IN clause' directly in the SQL statement of a query.

However, for data sources such as AS/400 (iSeries), SQL Server, and FoxPro (via newer database engines), Access requires an ODBC (Open Database Connectivity) connection string. This connection string defines how Access communicates with these external systems, specifying the driver, data source name, authentication credentials, and other parameters needed to establish the connection.

ODBC Connection String

The best way to learn and understand more about the Connection String Syntax of different ODBC Data Sources is to go through the following steps and look at the Connection String of the Linked Table:

  1. Create an ODBC DSN (Data Source Name). Refer to the Post Linking with IBM AS400 Tables.

  2. Link the Table from the source directly using File -> Get External Data -> Link Table.

  3. Select ODBC Databases in the Files of Type control.

  4. Select the ODBC DSN that you have created from the displayed list.

  5. Click OK. If you have not created a DSN, you can create a new one by selecting the New... Command Button.

  6. Select the Table to link with your MS-Access Database.

  7. After linking the Table, select the linked Table.

  8. Select Design from the Database Menu. You will receive a warning message saying that the Linked Table Structure cannot be modified. Click Yes to the Prompt: Do you want to open it anyway?

  9. Display the Property Sheet (View ->Properties).

Description Property of Table

On the Description Property of the Table Structure, you will find the ODBC String that can be used directly on the Query's SourceConnectStr Property.

A few examples of ODBC Connection String Values are given below:

AS400 (iSeries) Table:
  • ODBC;DSN=myData;UID=UserID;PWD=Password;TABLE=PAVUP.APC161D
SQL Server:
  • ODBC;DSN=MyData;UID=UserID;PWD=Password;DATABASE=Parts
FoxPro:
  • ODBC;DSN=Visual FoxPro Tables;UID=;PWD=;SourceDB=C:\MyFoxpro;SourceType=DBF;Exclusive=No;BackgroundFetch=Yes;Collate=GENERAL;Null=Yes;Deleted=Yes

As shown in the examples above, the DSN Name, User ID, Password, and other parameters in the ODBC connection string are specific to each data source and must be entered accurately to establish a valid connection to their respective tables.

In the case of the AS400 (iSeries) ODBC connection string, the table name and library (or folder) name are separated by a dot (.), following the convention used in IBM systems, for example, `MYLIB.MYTABLE`.

For more details on setting up such connections, you can refer to the earlier discussion titled “Linking with IBM AS400 Tables”, which explains how to properly link AS400 (iSeries) tables to a Microsoft Access database using ODBC drivers and connection parameters.

Earlier Post Link References:

Share:

PRESENTATION: ACCESS USER GROUPS (EUROPE)

Translate

PageRank

Post Feed


Search

Popular Posts

Blog Archive

Powered by Blogger.

Labels

Forms Functions How Tos MS-Access Security Reports msaccess forms Animations msaccess animation Utilities msaccess controls Access and Internet MS-Access Scurity MS-Access and Internet Class Module External Links Queries Array msaccess reports Accesstips WithEvents msaccess tips Downloads Objects Menus and Toolbars Collection Object MsaccessLinks Process Controls Art Work Property msaccess How Tos Combo Boxes Dictionary Object ListView Control Query VBA msaccessQuery Calculation Event Graph Charts ImageList Control List Boxes TreeView Control Command Buttons Controls Data Emails and Alerts Form Custom Functions Custom Wizards DOS Commands Data Type Key Object Reference ms-access functions msaccess functions msaccess graphs msaccess reporttricks Command Button Report msaccess menus msaccessprocess security advanced Access Security Add Auto-Number Field Type Form Instances ImageList Item Macros Menus Nodes RaiseEvent Recordset Top Values Variables Wrapper Classes msaccess email progressmeter Access2007 Copy Excel Export Expression Fields Join Methods Microsoft Numbering System Records Security Split SubForm Table Tables Time Difference Utility WScript Workgroup database function msaccess wizards tutorial Access Emails and Alerts Access Fields Access How Tos Access Mail Merge Access2003 Accounting Year Action Animation Attachment Binary Numbers Bookmarks Budgeting ChDir Color Palette Common Controls Conditional Formatting Data Filtering Database Records Defining Pages Desktop Shortcuts Diagram Disk Dynamic Lookup Error Handler External Filter Formatting Groups Hexadecimal Numbers Import Labels List Logo Macro Mail Merge Main Form Memo Message Box Monitoring Octal Numbers Operating System Paste Primary-Key Product Rank Reading Remove Rich Text Sequence SetFocus Summary Tab-Page Union Query User Users Water-Mark Word automatically commands hyperlinks iSeries Date iif ms-access msaccess msaccess alerts pdf files reference restore switch text toolbar updating upload vba code