Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Showing posts with label MsaccessLinks. Show all posts
Showing posts with label MsaccessLinks. Show all posts

Lost Links of External Tables

Introduction.

We have already learned several methods to work with external data sources. By linking them to 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 their original location all the time.

But, there is a possibility that the links to some of these tables can be lost either by deleting or renaming the source table by mistake. We will come to know about the error only when we attempt to work with the external tables and chances are that the error pops up in the middle of some process steps.

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 is 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 runs into an error, you can be sure that either it got deleted, or the name changed.

There may be several tables in a database, local as well as linked ones. How can we single out the linked ones alone and open them to check the status? Again, this is not a big 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 a Table from external data sources manually.

  1. Highlight Get External Data from 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. Find 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 from H:\ to K:\ or anything else, MS-Access will have no difficulty in finding the linked Table. Otherwise, you have to go for the Option Tools - ->Database Utilities - ->Linked Table Manager for refreshing the changed location reference of the table.

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

Here, we will try to 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 have to 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 Codes into a Global Module of your MS-Access Database and save them:

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 actions 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 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 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 usage of SourceConnectStr Property combined with Source Database Property of MS-Access Query can be used to open external data sources, like dBase, FoxPro (Version 2.5 or 3.0), and Excel Table, directly and work with them.

We have learned how to add the above Property specifications in an IN Clause directly in the SQL of the Query.

Data sources like AS400 (iSeries), SQL Server, and FoxPro need an ODBC (Open DataBase Connectivity) Connect String to get access to these System data.

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 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 you can see in the above examples that the DSN Name, User ID, Password, and other details are Data Source specific and must be provided correctly to get access to their respective Tables.

In the AS400 (iSeries) ODBC Connection String above the Table Name and Folder Name are separated with a dot in between. You may refer to the earlier Post Linking with IBM AS400 Tables to learn how to link AS400 (iSeries) Table to MS-Access Database.

Earlier Post Link References:

Share:

Access Live Data in Excel-2


Continued from last Week's Post

This is the continuation of the earlier Post Access Live Data in Excel. Please go through the earlier Article before continuing.

If you want to make changes to the Query that you have created for bringing Access Data into Excel you may do so.

  1. Click in a cell within the Data Area on the Worksheet.

  2. Point to Import External Data (Geet External Data in MS-Office2000) in Data Menu.

  3. Select Edit Query from the displayed menu. The Wizard will guide you through the earlier selections and you can modify them before saving the Query.

Microsoft Query.

Alternatively, you can open Microsoft Query Program (C:\Program Files\Microsoft Office\Office11\MSQRY32.EXE in MS-Access 2003) and open the saved Query (Refer earlier Post Access Live Data in Excel for Query File's default location) from the File Menu, edit the SQL String and view the Output data in the Query Editor before saving the changes.

When you open the Query that you have created and saved earlier the Source Data will be displayed in Datasheet View. Click on the SQL labeled Toolbar Button or select SQL from the View menu.

You will find the SQL String like the sample given below:

SELECT Categories.CategoryID,
 Categories.CategoryName,
 Categories.Description,
 Categories.Picture
FROM `C:\Program Files\Microsoft Office\Office11\samples\Northwind`.Categories Categories

The normal SQL terminator character semicolon (;) is not present. The FROM Clause in the SQL is written differently without the use of an IN Clause, which we have seen in the MS-Access Query to Open Excel or dBase Tables directly using Source Connect Str Property. The Categories Table Name is attached to the sample Database Path Name with a dot separator and the Table Name is repeated with space in between. The .mdb file extension to Northwind is also omitted from the database file name specification.

If you Copy and paste the above SQL String into an MS-Access Query and change it into Datasheet View it will display the data correctly. No errors will be displayed except some Column headings may appear as Expr3, Expr4, and so on, if you have changed the Query in Design View first and then switched into Datasheet View.

Properties of Microsoft Query

This is the time to learn the usage of two more Properties of MS-Access Query.

  1. Copy the above SQL String into a new MS-Access Query SQL window.

  2. Select View - -> Datasheet View to display Records from the Categories Table from the Northwind.mdb database.

  3. Select View - -> Design View to change the Query Design View.

  4. The Table Object has been already visible on the Query Design surface, but the Field Names are absent. Click on the title area of the Table to select it.

  5. Display the Property Sheet (View - -> Properties. The Alias and Source Properties of the Query are displayed.

  6. The Table Name Categories are loaded in the Alias Property and the Path Name of the NorthWind database is appearing in the Source Property without the .mdb extension.

  7. Change the Table Name appearing in the Alias Property into something different, say myCategories.

  8. Add .mdb extension at the end of the Pathname string in the Source Property.

The Table Name now appears as myCategories on the Title of the Table. If you change the Query in SQL View you can see that at the end of the SQL String the reference to the Table name, Categories Categories (appeared twice earlier) has now changed to Categories As myCategories.

We must qualify each data field with the Table Name myCategories due to the Alias Name change. Change the SQL String as shown below to qualify each Field with the Alias Name. Enclose the Database Path Name in Square Brackets ([]) in place of the single quotes.

SELECT [myCategories].[CategoryID],
 [myCategories].[CategoryName],
 [myCategories].Description,
 [myCategories].Picture
FROM [d:\Program Files\Microsoft Office\Office\samples\Northwind.mdb].Categories AS myCategories;

The manual change is necessary because we are referencing an external data source and no way MS-Access can guess the name. If we are using a Table from within the Database or a linked Table then the Alias Name change will automatically take effect in all the fields. You may try this experiment with one of your own Tables from within the Database or with a linked Table.

Note: The Source Database and Source Connect Str Property Values are taken into the Query Syntax with an IN Clause to identify the external Application.

Alias Property is initially set with the Table Name and accepts changes to the Table Name through this Property.

Source Property accepts the external Database reference, either direct Path Name or an ODBC Connection String, and the SQL Syntax is different in the FROM Clause of the Query definition.

Earlier Post Link References:

  1. Roundup Function in Excel in MS-Access
  2. Proper Function in Excel in Microsoft Access
  3. Appending Data from Excel to Access
  4. Writing Excel Data Directly into Access
  5. Printing MS-Access Report from Excel
  6. Copy Paste Data From Excel to Access2007
  7. Microsoft Excel-Power in MS-Access
  8. Rounding Function MROUND of Excel
  9. MS-Access Live Data in Excel
  10. Access Live Data in Excel- 2
  11. Opening Excel Database Directly
  12. Create Excel, Word File from Access
Share:

MS-Access Live Data in Excel


Introduction.

We have already learned a few tricks to open and work with external data sources like Access Table, dBase Files, and Excel Table without linking them permanently. We have tried VBA and Query-based methods too.

We have yet to try the ODBC connection string in Source Connect Str Property in a Query to open external data files with this method. Even though we can link external data into MS-Access manually, we will be trying the VBA-based method for linking external files later.

But, before going into all that we will try a different trick, for a change in the one-way traffic, so to speak, of data flow from external data sources into Access. But it is not exactly one-way data flow into Access we can update external data from within Access, with or without direct links.

The Data Sources that we have opened after setting Source Database and Source Connect String Properties in Queries are updatable. The changes which you make on these data sets from within MS-Access will be updated back in their respective parent Applications.

Live MS-Access Data in Excel Sheet

Here, we will try linking live MS-Access Data in Excel and see that it stays on reflecting changes made in MS-Access. MS-Access will function as the Server Application and MS-Excel will be on the Client side.

There is only one difference when compared with the earlier methods we tried, the changes that you make to Access data in Excel, which you are allowed to do, will not be updated back in Access.

Then what do we do with the Access Data in Excel? Well, you can create Charts or do calculations or whatever you like if you are more comfortable with Excel-based tasks. You can create links to the data (Copy- -> Paste Special- ->Paste Link) from other parts of the Workbook and use the data for Charts or Reports, instead of making the direct change to the linked source data. The changes that take place in Access will automatically reflect on the Report or Chart in Excel.

For bringing Access Data into Excel we need another Application, Microsoft Query, as a go-between, to connect to Access Table. The Query Wizard will guide us through the various options to link with Access when we start with the Data options in Excel.

We will use the Categories Table from Northwind.mdb sample Database for our example.

Step through the following procedure.

  1. Open a new MS-Excel Workbook.

  2. Select Cell A1 on Sheet1.

  3. Point to Import External Data in Data Menu.

  4. Select New Database Query from the displayed menu.

    Now, the Microsoft Query Wizard Opens up and displays a Dialog Box. It displays the Database Sources in the Databases Tab that you can link to MS-Excel. This is a combined list of items appearing in the ODBC Dialog Control User DSN, System DSN, and File DSN Tabs.

  5. Select MS-Access Database* from the list and click OK.

  6. The Common Dialog Control opens up, allowing you to browse to the Location of MS-Access Database and select it. Find the sample database C:\Program Files\Microsoft Office\Office11\Sample\Northwind.mdb (MS-Access 2003, you can drop 11 from Office11 in the location address for Access 2000), select and click OK.

  7. Select the Categories Table from the Available Tables and Columns in the Query Wizard and click on the > symbol to select all the Fields of the Categories Table into the Columns in your Query Control. If you don't need all the fields from the Source Table then you can expand the Categories Table by clicking on the + symbol to display all the Fields and select only those you need and move them to the right side.

    Before you move the field to the right, you can preview the Field contents by clicking the Preview Now button below. Memo Field or OLE Object field contents cannot be previewed this way.

  8. After selecting the Fields Click Next. Here, you can define Filter conditions.

  9. Click Next to proceed to the Sort options.

  10. Click Next to move to the Finishing point.

    Here, we have the option to save the selected settings in a Microsoft Query (which is an external File) at location C:\Documents and Settings\User\Application Data\Microsoft Queries\. If we need any changes in the data selection options, then we can open this saved file in Microsoft Query and edit the Query Definition in SQL Window.

  11. See the Radio Button set on Return Data in Microsoft Office Excel and click Finish.

  12. In the next Dialog Control, you can select the Location on the Excel Sheet, where you want to insert the data from Access. Since we have already selected Cell A1 as the target location in Step-2 above, this will appear as the default location in the control, click OK without change.

The records from the Categories Table will be inserted in Excel starting from range address A1.

It was a long journey from Access to Excel. Bringing Excel data into Access needs only two property changes in MS-Access Query and you know now how simple it is.

Refreshing Updates from Access Table.

Since we are successful in bringing Access data into Excel let us do some experiments to prove that it is really live data from Access and how the changes made in Access reflect here.

There are two methods to refresh Access Data in Excel, Manual and Automatic.

Keep the Northwind.mdb sample database open so that we can make changes in the linked table in Excel or in Access and check the results of the change in both Applications.

  1. Open the Categories Table of Northwind.mdb Database.

  2. Add Crabs, and Lobsters in the Description field of the last record. Or add a new record with some Category Name and Description.

  3. Minimize MS-Access and Display Excel Window and check whether the change has taken place immediately in the linked data in Excel. You may not find any change on the Excel side. We have to refresh the data in Excel to reflect the changes.

  4. Click anywhere within the data Area.

  5. Select Refresh Data from Data Menu.

    Now the changes that you have made will be updated on the Excel side too. We can tell Excel to do this job automatically at a fixed interval rather than doing it manually.

  6. Right-Click somewhere in the middle of the Linked Table and select Data Range Properties from the displayed Shortcut Menu.

  7. On this Control, you will find several options to manage the Data including the Query Name that transports the data from Access to Excel. Select the Radio Button in the Refresh Every option under the Refresh Control Option Group and set the time 1 Minute, so that we can watch the refreshing action without waiting for it for too long to happen.

  8. Open the Access window and remove the changes that we have made in the Categories Table, or make some more changes so that they are clearly visible in Excel when automatic refreshing action takes place.

  9. Open the Excel window and wait for the Refresh Action to take place. The change might have already taken place or it may happen at any time because Excel will continue to refresh the change every minute.

If you have made any changes in the Excel side of the data, then that will be lost in this process.

If you close the Excel Workbook and open it again a prompt will pop up asking you to re-confirm whether Excel should automatically do the refreshing of linked data or not. You may respond the way you want it.

We will continue our discussion on a few more points on this subject in the Next Post, instead of crowding everything in here.

  1. Roundup Function in Excel in MS-Access
  2. Proper Function in Excel in Microsoft Access
  3. Appending Data from Excel to Access
  4. Writing Excel Data Directly into Access
  5. Printing MS-Access Report from Excel
  6. Copy Paste Data From Excel to Access2007
  7. Microsoft Excel, Power in MS-Access
  8. Rounding Function MROUND of Excel
  9. MS-Access Live Data in Excel
  10. Access Live Data in Excel- 2
  11. Opening Excel Database Directly
  12. Create Excel, Word File from Access
Share:

Database Connection String Properties

Introduction.

Opening external data sources like dBase, Excel, and Table from another MS-Access Database directly in VBA Code is only one of the options available to us. Those who are not comfortable with VBA have a better and much easier method available, without linking them permanently to MS-Access Database. In either case, one thing is certain, we must know how to reference different external data sources correctly with Source Database Path and Connection String Values. These methods are very easy to learn.

We may face little difficulty in finding ODBC (Open Database Connectivity) Connection string Syntax, but this also we can find out by going through some shortcut tricks. Let us not mix this with the ODBC part now with our current example and we will deal with it later.

We have seen that we can display Values from Excel Cells or Range directly on MS-Access Form controls.

After going through the earlier examples for opening Access Table, dBase Table, and Excel tables directly in VBA, I hope at least a few readers thought of copying the SQL string presented in the VBA Code into a Query and trying them out. If not, it is time to do that. It is a better option to understand them and to look into a few things associated with their usage.

Open Recordset in Select Query, from External Access Database

To start with, let us try to open an MS-Access Table from another Database directly in a Select Query.

  1. Open one of your Databases or create a new one.
  2. Select the Query Tab and Click the New Button on the Database Menu. Select Design View from the displayed Options and Click Close without selecting any Table from the list.
  3. Click on the SQL Toolbar Button or select SQL View from View Menu.
  4. Copy and Paste the following SQL String in the SQL Editing Window, Save the Query with the Name EmployeesQ.
    SELECT Employees.* 
    FROM Employees IN 'C:\Program Files\MicrosoftOffice\Office\samples\Northwind.mdb';

    Note: If you are using MS-Access2003 then change the Path to . . .\Office11\Samples\.

  5. Open the Query in Datasheet View (View - -> Datasheet View) to display the Employees Table contents from the Sample Database Northwind.mdb.

In the SQL String, an IN Clause is used for pointing to the correct database path, and the entire Path Name is put in quotes and ends with a semi-colon indicating the end of SQL String, which is applicable for all Queries.

A Different and simple Method

There is another way that you can do this. But, the first part you have to write in SQL window, and the IN Clause part we can add separately in the Source Database and Source Connection Str properties of the Query so that you don't have to remember where to put the word IN or where to put the Opening/Closing quotes or worry about such syntax issues.

  1. Create a New Query and open the SQL editing window following Steps-1 to 3 explained above.
  2. Write the SQL string SELECT Employees.* FROM Employees;
  3. Select Design View from View Menu, to change the Query from SQL View in Design View. We are now in the normal Query Design View. You will find the Employees Table object appearing in the Query Design without any Field Names showing in it.
  4. Select Properties from View Menu to display the Property Sheet of the Query.
  5. Click on an empty area of the Query surface, to the right of the Table Name, to display the Query level Property Sheet correctly.
  6. There are two properties on the Property Sheet that we are interested in.
    • Source Database
    • Source Connect Str

    Here we will be using only the Source Database Property for the external MS-Access Table.

  7. Enter the following Path Name in the Source Database Property over-writing the text (current).

    C:\Program Files\Microsoft Office\Office\samples\Northwind.mdb

    Or with the change explained above for MS-Access2003 cases.

  8. Select Datasheet View from View Menu.

You will now see the same result as the first Select Query we tried. If you change the Query into its SQL View and inspect the SQL String, you can see that the IN Clause is formed using the Source Database property Value.

Source Connect Str for dBase and Excel

You can use the same method for dBase Table and Excel Table (Named Range). In these cases, we have to use the Source Connect Str Property also.

Example: opening the dBase Table directly.

Table Name : Customer.dbf

SQL String: SELECT Customer.* FROM Customer;

Source Database Property Value = C:\mydBase

Source Connect Str Property Value = DBASE IV; (check the semicolon at the end)

Replace the Customer table name and the Path C:\mydBase location address with your own dBase File Name and Folder name, where the dBase Table is located.

Example: opening Excel Table (Named Range) direct.

Table Name: Categories

SQL String: SELECT Categories.* FROM Categories;

Source Database Property Value = C:\My Documents\Products.xls

Source Connect Str Property Value = Excel 5.0;

(note the semicolon at the end)

Replace the Categories table name and the Path C:\My Documents\Products.xls Excel file with your own.

NB: You must first define the Name Categories in Excel Table Range use Insert - - > Name - - > Define before attempting to use the name Categories in MS-Access Queries.

Next: MS-Access Live data in Excel

Earlier Post Link References:

Share:

Opening Excel Database directly

Introduction

In the World of Personal Computers, many Applications came and disappeared. One of the very popular Applications was WordStar (Word Processor) used under Operating Systems CP/M (Control Program for Microcomputers) and DOS (Disk Operating System) till 1992. There were dedicated Word Processing Machines in those days using WordStar and competing Software WordPerfect. Microsoft Excel is also one of the very early days of Applications, since 1985, and we all know how popular it is.

The first Worksheet Program Visicalc came out in 1979 with a bang and branched out into several names Supercalc, Multiplan, Lotus 1-2-3, Microsoft Excel, and others putting more power into these clones than the original Worksheet Program Visicalc. (Source: Wikipedia)

Like Microsoft Access, Microsoft Excel also has very powerful Automation features that can make Excel computing very interesting.

Spread Sheet Programs are designed for analysis that involves a chain of calculations with all the information spread across the Sheet visible to the user. A small change at the beginning of the calculation triggers a chain reaction across the cells, which have a formula that depends on other cells, and the end result is instantaneous. It is an invaluable tool for What. . If. . . Analysis. When we think about Graph Charts the first name that comes into our mind is Microsoft Excel.

Excel Table

With limited features of Database Functions also built into it with the power of Filter, Sort, etc. This is where we step in to introduce a Table in Excel for our new example for Reading/Updating the Excel data from Access.

Even though there are facilities in Excel to implement general database rules for creating and maintaining a table it is often not followed. It is left to the user to decide how to create a worksheet and how to create a database when both can go into a single Worksheet side by side.

In Access, there are strict rules that we should follow, like should not enter text in Numeric Field, or cannot enter Text larger than the field size, Field Names must be unique, and so on. All these rules are applicable in Excel also. But unlike in Access if we don't comply with any of these rules it may not give you an indication to correct it, but it will not work as you have originally planned. All the Data Field Types available in Access are not present in Excel, like True/False in Access, but these constants are valid values in Excel Cells.

Before we quickly introduce a database in Excel and open it directly in Access, as we did for dBase File, let us look into an example of setting field Validations in Excel to restrict Data Entry in a Cell. You will be surprised to see how powerful it is.

Validation Settings.

Example: Accept only values between 25 and 100 in a Cell or Cells.

  1. Open Excel and select a Cell in Sheet1.

  2. Select Data- -> Validation . . . - -> Settings.

  3. Select Whole Number in the Allow: Control.

  4. Enter 25 in the Minimum Control and 100 in the Maximum Control.

  5. Select the Input Message Tab. Enter Age in the Title Control and type Enter Value between 25 and 100 in the Input Message.

  6. Select Error Alert Tab and type Value Error in the Title Control.

  7. Type Valid Value between 25 and 100 in the Error Message Control and Click OK to close it.

Try entering a value less than 25 or greater than 100 in this cell, it will display the Error message that you have set up in the Validation Control.

You can apply the same rules quickly to other cells. Copy the Cell, highlight the Range of Target Cells and select Edit - -> Paste Special - -> Validation. If you paste it over existing data it will not validate the field contents if the wrong value is already present in the Cell. The validation check is performed only when you manually key in values.

Following the same procedure try setting a validation rule in a Cell to accept only Text Length, Less Than, 15 characters. Try entering 16 characters or more into that Cell.

When we plan for creating a database in Excel we can define short and meaningful Headings on the top row to stand for Field Names and set up Data Entry rules, following the procedure explained above, for each Field cell so that they will accept only valid values into them. You already have a Data Entry/Search Form in Excel like in Microsoft Access.

If you have a Data Table in Excel, then click anywhere within this Table, and select Form from Data Menu. You will get a Data Entry/Search Form. Clicking the Criteria Command Button will turn it into a Search Form, that you can enter Search Criteria into the Field, which you want to use to find your record. You can try this after we create a Table in Excel quickly, for our VBA Program to open the Excel Table directly in MS-Access.

Preparing for a Trial Run.

  1. Open Microsoft Excel (if you have closed it).

  2. Open the NorthWind.mdb sample database. Check the link Saving Data on Forms not in Table for location references, if you are not sure where this file can be found.

  3. Open the Categories Table in Datasheet View.

  4. Right-Click on the top left corner of the Datasheet View and select Copy from the shortcut menu.

  5. Click on the Excel Icon on the Taskbar to open it and select Cell A1.

  6. Select Paste from Edit Menu.

  7. While the highlighting is still on the pasted Table, select Insert - ->Name - -> Define and type Categories in the Names in Workbook Control and Click OK to close it.

  8. Save the Workbook with the name: C:\My Documents\myData.Xls and close Microsoft Excel and close the Northwind.mdb sample Database.

  9. Open any one of your Databases or create a new one.

  10. Copy and paste the following code into the Global VBA Code Module of your Database and keep the Module open. You may save the Module by selecting the Save Toolbar Button or with the File - -> Save option.

    Public Sub OpenDirectExcel()
    '-----------------------------------------------------
    'Open Excel Table directly
    'Author : a.p.r. pillai
    'URL    : www.msaccesstips.com
    'All Rights(c) Reserved by msaccesstips.com
    '-----------------------------------------------------
    Dim db As Database, rst As Recordset
    Dim strSql As String, i As Integer
    Dim msg As String
    
    strSql = "SELECT Categories.* FROM Categories IN 'C:\My Documents\myData.xls'[Excel 5.0;];"
    Set db = CurrentDb
    Set rst = db.OpenRecordset(strSql, dbOpenDynaset)
    
    i = 0
    With rst 
    msg = ""
    Do While Not .EOF And i < 5
       msg = msg & ![Category Name] & vbCr
       If ![Category Name] = "Confections" Then
          .Edit
          ![Category Name] = "Chocolates"
          .Update
       End If
       i = i + 1
       .MoveNext
    Loop
    .Close
    End With
    
    MsgBox msg, , "Product Categories"
    
    Set rst = Nothing
    Set db = Nothing
    
    End Sub
    
  11. Click in the middle of the Code and press F5 to run it. Displays the Product Category Names of the first five Records from the Categories Table in C:\My Documents\myData.xls in a Message Box.

Note: In the VBA Code we have tested the Category Names Field for the value Confections and updated the Value Chocolates back into Excel Cell overwriting the word Confections.

Check the SQL Syntax in the Code that pulls the data directly from the Named Range Categories in C:\My Documents\myData.xls file.

  1. Microsoft Excel and Automation
  2. Microsoft Excel and Automation-2

Next: Database Connection String Properties

Earlier Post Link References:

  1. Roundup Function
    of Excel in MS-Access
  2. Proper Function of Excel in Microsoft Access
  3. Appending Data from Excel to Access
  4. Writing Excel Data Directly into Access
  5. Printing MS-Access Report from Excel
  6. Copy Paste Data From Excel to Access2007
  7. Microsoft Excel Power in MS-Access
  8. Rounding Function MROUND of Excel
  9. MS-Access Live Data in Excel
  10. Access Live Data in Excel- 2
  11. Opening Excel Database Directly
  12. Create Excel Word File from Access
Share:

Display Excel Value Directly on Form

Introduction - MS Access2003

We have already seen how to open dBase Files directly and work with the data in VBA in the earlier Post Opening dBase File Directly. But, there are other alternatives (besides linking the files) to work with dBase Files in Access. We will explore this aspect in detail later. This post was originally intended for a demo of opening an Excel-based Data Table directly and working with it in the VBA Code. We will do that in the next post. Before that, we will look into some interesting and very easy tricks with Excel.

Why I said very easy because you don't have to struggle with VBA Code to do this. I know you will be happier if you don't have to work with my spaghetti VBA Code. So, I thought we take a break and do something different and interesting before continuing with databases.

You got the clue from the title itself. That's right, you can display Values from Excel Worksheet directly on Microsoft Access Forms. We will go straight into a Demo.

The Demo Run Preparation

  1. Open Microsoft Excel.
  2. Enter your name in cell A1 on Sheet1 and minimize Excel, don't close it. You may save the Workbook with a name before minimizing it. The WorkBook may keep interrupting for saving it if the Auto-save feature is on.
  3. Open any one of your Microsoft Access Databases or create a new one.
  4. Open a New Form in Design View.
  5. Select the Text Box Tool from the ToolBox and draw a Text Box on the Detail Section of the Form.
  6. Click on the Text Box and display the Property Sheet (View - -> Properties).
  7. Write the following expression in the Control Source Property of the Text Box:

    =DDE("Excel","Sheet1","R1C1")

  8. Save the Form with the name of your choice.
  9. Open the Form in Normal View. You will see your Name written on Excel Cell appearing in the Text Box on the Form.

    The DDE() Function stands for Dynamic Data Exchange. The first two Parameters are Excel Application and worksheet name Sheet1 and the third one is the Cell Reference where your name is written in R1C1 (Row-1 Column-1 or Cell A1). Cell reference must be used in this way rather than the A1 style.

    Do the following, if not successful.

    But, there are chances that you may end up with nothing showing on the TextBox. In that case, you have to see if a particular Option is set correctly on the General Tab of Options in the Excel Tools Menu.

  10. Click on the Excel icon on the Taskbar to open it. Click on Tools - -> Options, and select the General Tab.
  11. Remove the checkmark (if it is set) from the option Ignore Other Applications under the Settings Options.
  12. Minimize Excel, Close MS-Access Form, and open it again. Now you must see your name from the Excel Cell on the Form. Don't close the Form.
  13. Maximize Excel again and make some changes in your Name and Minimize again. The change may not reflect immediately on the Form. You can update the Form value manually without closing and opening the Form again.
  14. While the Access Form is in Normal View, select OLE/DDE Links from Edit Menu.
  15. The Links Dialog Box will open up. Select DDE Links in the Links Group control. The Link's list will appear below. Select the Link and click on the Update Now Command Button. Now the change on the Worksheet will reflect the Form Value.

There are Option settings in MS-Access also similar to the one we have made in Excel. The general rule is that instead of refreshing the change manually, as we did above, it should happen automatically at a fixed interval as per the Tools - - > Option settings in Microsoft Access, but I didn't see it happen successfully on my machine so far.

Select Tools - -> Options. . . - -> Advanced Tab. Put a check-mark in the Enable DDE Refresh option, if it is not set. You can see the default Values set for automatic refreshing for Dynamic Data Exchange and ODBC links, how many retries, and in case of failures how long Microsoft Access should wait before trying again, etc.

Display Value in Combo Box and Option Group

You can display Values from Excel in two more Access Controls, Combo Boxes and Options Group Control. See the sample image given below.


The Combo Box Method

  1. Minimize Access and Maximize Excel.
  2. Enter a few Names of people, books, or anything else in Cells A9 to A17.
  3. Enter Value 2 in Cell C1 and minimize Excel Application Window.
  4. Maximize MS-Access and open the Form in Design View.
  5. Disable the Control Wizards Button (top right button, if it is active) on the ToolBox. Select the Combo Box Tool and draw a Combo Box Control on the form in such a way that it looks like a List Box. See the sample image given above.
  6. Display the Property Sheet and write the expression
    =DDE("Excel","Sheet1","R9C1:R17C1")

    In the Control Source Property of the Combo Box.

    You may give a Name to the Range: R9C1:R17C1 and use that Name in the expression replacing the Range Address. To Name the Excel Cell Range, highlight the Range, select Insert - -> Name - - > Define and type the name, say List, in the Names in Workbook control. Replace the third Parameter R9C1:R17C1 with the Range Name List in the DDE Function.

  7. Open the Form in Normal View. The Names from the Excel Range will appear in the Combo Box.

Note: You cannot select any of these values and insert them into the Text Box portion of the Combo Box and use it in a data field.

The Option-Group Option

We will try one more example with the Options Group Control.

  1. Turn On the Control Wizard on the ToolBox. Select the Option Group Tool from the ToolBox and Draw an Option Group Control on Form. Refer to the example given above.
  2. Type three Labels in the Wizard: Data View, Print Preview and Print, or anything else you prefer, on the control and Click Finish.
  3. Click on the outer frame of the Options Group and display the Property Sheet (View -> Properties).
  4. Write the following expression in the Control Source Property:
=DDE("Excel","Sheet1","R1C3"

The selection of items on the Option Group will be based on the value given in Excel Cell C1. Now the value in Cell C1 is 2. The second item in the Options group will now show as selected. Change the Value in Cell C1 to 3 and refresh the Form as explained above, the option will change to 3.

Note: If the Excel Application is not active when you open the Form with the DDE() Function then Access will show the following Error Message:

"You tried to open a form or report that includes a DDE or DDESend function in a calculated control that specifies an OLE server application."

"Do you want to start the application Excel?"

If you respond with Yes then Excel Application will be started with Blank Sheets. You must open the Excel Workbook that provides information for DDE() Function manually to show up the values in Access Form.

Next: Opening Excel Database directly.

  1. Roundup Function of Excel in MS-Access
  2. Proper Function of Excel in Microsoft Access
  3. Appending Data from Excel to Access
  4. Writing Excel Data Directly into Access
  5. Printing MS-Access Report from Excel
  6. Copy Paste Data From Excel to Access2007
  7. Microsoft Excel Power in MS-Access
  8. Rounding Function MROUND of Excel
  9. MS-Access Live Data in Excel
  10. Access Live Data in Excel- 2
  11. Opening Excel Database Directly
  12. Create Excel Word File from Access
Share:

Opening dBase Files Directly

Introduction

In the earlier Article Opening External Data Sources, we learned how to open another Microsoft Access Database and work with its Tables using the code. I have made a revision of the VBA Code taken from the earlier Post and presented below, to display the Database Names loaded in WorkSpace(0), on top of the list of Employee Names in the MsgBox. The Revised Code is given below. You may copy and replace the earlier Code and try them out.

Revised VBA Code.

Public Sub OpenSecondDatabase()
Dim wsp As Workspace, db As Database
Dim rst As Recordset, msg As String, x As Integer
Dim dbcount As Integer

Set wsp = DBEngine.Workspaces(0)
Set db = wsp.OpenDatabase("c:\Program Files\Microsoft Office\Office11\samples\Northwind.mdb")
Set rst = db.OpenRecordset("Employees", dbOpenDynaset)

dbcount = wsp.Databases.Count - 1

msg = ""
For x = 0 To dbcount
 msg = msg & "Database(" & x + 1 & ") " & Dir(wsp.Databases(x).Name) & vbCr
Next
msg = msg & vbCr
With rst
x = 1
Do While x < 6 And Not .EOF
    msg = msg & ![LastName] & vbCr
   .MoveNext
   x = x + 1
Loop
   .Close
End With
MsgBox msg

Set rst = Nothing
Set db = Nothing
Set wsp = Nothing
End Sub

The statement wsp.Databases(x).Name gives the full Path Name of the File and I have enveloped it in the Dir() (Directory Function) to extract the Database Name alone to make it shorter in the MsgBox display. The Dir() function checks for the presence of the Database in its specified Folder and if found returns the File Name alone.

Opening dBase Table

Opening the dBase File is comparatively a simple operation. Create an SQL string with a reference to the dBase Database Folder, the Table Name, and the dBase Version (dBase III, IV, or 5.0) of the Table and open the Recordset directly. The sample SQL String is given below:

strSql = "SELECT Employee.* FROM Employee IN 'C:\MydBase'[DBASE III;];"

If you don't have a dBase file on your Machine to try this out you can Export one of your own Microsoft Access Tables to dBase III, IV, or 5.0 Versions.

I have used the exported Employees Table from the NorthWind.mdb sample database in our example. If you would like to try the Code given below without change, you may Export the Employees Table from the Northwind.mdb sample database. If you are not sure, where you can find this file, visit the Page Saving Data on Forms Not in Table, for location references.

Exporting Employees Table as dBase Table

  1. Create a Folder on your Disk C:\MydBase.
  2. Open the Northwind.mdb database.
  3. Select the Employees table.
  4. Select Export from File Menu.
  5. Select dBase III or dBase IV or dBase 5 in the Save as Type Control in the Common Dialog Box.
  6. Browse to the Folder C:\MydBase.
  7. Type the File Name Employee in the File Name Control and Click Export.

Note: dBase Application File uses only 8 characters for the name and 3 characters, for File Name Extensions. When you Export the Employees Table it will shorten the name to 8 characters and saves it as file Employee.dbf. The exported Table's Field Names also will be truncated after the 10th character, if they are longer.

When the Employees Table is Exported in dBase format, several files are created in the output folder depending on the Version of dBase (III, IV, or 5.0) you have selected. The list of files will look like the samples given below:

  1. EMPLOYEE.INF (contains the Index File Details)
  2. EMPLOYEE.DBF (the data except for the Memo Field Values)
  3. EMPLOYEE.DBT (the Memo Field contents)
  4. LastName.NDX (LastName Field Index information if saved as dBase III)
  5. Postalco.NDX (PostalCode Field Index information if saved as dBase III)
  6. PRIMARYK.NDX (PrimaryKey Index information if saved as dBase III)

If you export the Table, in dBase IV or 5.0 format, then the information in the last three files will be saved into a single Multiple Index file with the file extension.MDX. The Export, Import, or Link operations are influenced by the dBase Driver known as ISAM stands for Indexed System Access Method), a common method used by dBase, FoxPro (up to Version 3.0), etc.

When you attempt to link a dBase Table to your MS-Access Database it will look for all these related files to load information correctly into Access. Assume that you have deleted the File EMPLOYEE.DBT from the folder, then the Table Import or Link operation fails with the error: cannot locate the XBase memo file.

You may Export the Employees Table into a dBase IV and 5.0 Versions as well to try opening with SQL Syntax for these Versions also. But you can use dBase III Version syntax to open other Version Tables also.

We have gone through all the fundamentals that we need to know about dBase Files, and it is time to open and work with the data. Copy and paste the code given below into a Global Module of your Database and select File- - >Save to save the Module. Click in the middle of the Code and press F5 to Run the Code.

A MsgBox will open up displaying the LastName field contents from the Employee.dbf File. If you are trying with one of your own dBase files, then change the Code to insert your Table Name and Field Name.

VBA Code for Opening dBase Table

Public Sub OpenDirectDBF()
'Open DBase File directly and read contents
Dim db As Database, rst As Recordset
Dim strSql As String, i As Integer
Dim msg As String

strSql = "SELECT Employee.* FROM Employee IN 'C:\MydBase'[DBASE III;];"

'Syntax for dBase IV & dBase V
'strSql = "SELECT Employe4.* FROM Employe4 IN 'C:\MydBase'[DBASE IV;];"
'strSql = "SELECT Employe5.* FROM Employe5 IN 'C:\MydBase'[DBASE 5.0;];"

Set db = CurrentDb
Set rst = db.OpenRecordset(strSql, dbOpenDynaset)

i = 0
With rst
msg = ""
Do While Not .EOF And i < 5
   msg = msg & ![LastName] & vbCr
   i = i + 1
   .MoveNext
Loop
MsgBox msg
.Close
End With

Set rst = Nothing
Set db = Nothing
End Sub

Tips: Even if you use the Table Name with more than 8 characters in the SQL Syntax (say Employees having 9 characters), it will ignore the s character after the 8th character and will open the file correctly. You may enable the SQL statements given in the Code for other versions of dBase by removing the single quote (') character at the beginning and try running the Code. If you have FoxPro version 2.5 or 3.0 installed on your machine, then replace [DBASE III;] with [FoxPro 2.5;] or [FoxPro 3.0;] to try with these files. Later Versions of FoxPro use DSN-based Syntax.

Displaying Excel Value directly on Access Form is next.

Earlier Post Link References:

Share:

Opening External Data Sources

Introduction.

Linking external data sources like dBase, Excel, or Tables from some other Microsoft Access Database, in a Back-End, Front-End scenario, are the most common and efficient method to work with data, besides Tables from within the Database. If such Data Sources are linked to the Access database, then it is easy to build queries on them to process and prepare customized Reports, or Design Forms to Add/Modify Data from within Access. The Source data can remain in the parent Application for updating information. We can work with the linked Tables with the same ease as using Tables from within except for modifying the structure of the linked Table.

To link a Table manually, highlight Get External Data in File Menu and select Link Tables from the displayed menu. The Common Dialog Box will be displayed and you can browse to the location of another MS-Access Database, dBase File, or Excel File and select it. They will expose Objects that can be linked to the MS-Access Database.

If the source data is an Excel Database then it is better to give a Range Name (using Insert- -> Name - -> Define Option) to the whole range of Data Area before attempting to link with MS-Access Database. The main issue with the Excel-based data sources is that if the data is copied and pasted from other sources like Word or Text files then the Data Type will get mixed up in columns and the data will show #Error in those cells when we open it in Access.

Even though Excel Cells can be set with Data Validation Options for manual data entry, like accepting only integer values in Cells in a Column, or set the limit for accepting the number of characters in Cells in a Column, like maximum to 25, or accept Date or Time only and so on, but these are seldom used in Excel.   

So far we were discussing working with external data tables after manually linking them to MS-Access. We will see later how to Link external files using VBA without using the Menu Options highlighted above.

If we don't need a permanent link with the external table but we need data from it then we can open it directly from Access and work with the data.

Opening a second Access Database

To start with this method, we will try to open another Microsoft Access Database and read data from a Table with Code. We will see later examples of opening dBase File and Excel Databases to read data from these data sources as well.

Normally, after launching Microsoft Access we will open only one Database and that is always visible on the Application Surface unless we hide it through the Startup Option. We already knew that Microsoft Access is a component-based Application and it consists of several Objects and all of them are organized in the hierarchical Order. 

Application Object is the topmost one and we are opening it manually every time when we want to do something in Microsoft Access. We can create Microsoft Access Application Object from other Systems like Visual Basic and work with Microsoft Access Databases. 

The second in command is the Data Access Objects (DAO) at the top of all the other Objects like DBEngine (known as Jet Engine), Workspaces Collection, Databases Collection, User Groups, Users, Containers, Documents, Table Definitions, Query Definitions, and so on. Let us look into a graphical representation of the arrangement of some of these components, a few of the topmost ones because we are going to use them to open our second database and to read the contents of a Table from it.

The Jet Database Engine is the driving force behind our work with MS-Access Databases and it supports several WorkSpaces. We normally Load or Creates our Database(s) in Workspace(0).

The Database Security details like UserGroups, Users, PersonalIDs (PIDs), and Passwords are maintained by Data Access Objects (DAO) in a separate Workgroup Information Database with .mdw Extention. The active Workgroup File Name associated with the current Workspace can be checked by reading the DBEngine.SystemDB property. The DBEngine holds the Default UserID and Default Password associated with the active Workspace.

Displaying Workgroup Information File Name.

Type the following command in the VBA Debug Window:

? DbEngine.SystemDB

Sample Output: C:\mdbs\System.mdw

Databases in WorkSpace(0)

We will go back to the topic of the Workspace(0) and proceed further. We must set a reference to DBEngine.Workspaces(0), where our current database resides, to open a second Microsoft Access Database within the same Workspace to read/write data from/to its Tables. If you want to add another field to the Table you can do it as well.

To demonstrate a simple example we will open the Employees Table from the sample NorthWind.mdb Database and display the LastName Field contents in a MsgBox control with the following few lines of Code:

Public Sub OpenSecondDatabase()
Dim wsp As Workspace, db As Database
Dim rst As Recordset, msg As String

Set wsp = DBEngine.Workspaces(0)
Set db = wsp.OpenDatabase("c:\Program Files\Microsoft Office\Office11\samples\Northwind.mdb")
Set rst = db.OpenRecordset("Employees", dbOpenDynaset)

With rst
msg = ""
Do While Not .EOF
    msg = msg & ![LastName] & vbCr
    .MoveNext
Loop
   .Close
End With
MsgBox msg

Set rst = Nothing
Set db = Nothing
Set wsp = Nothing
End Sub

Copy and Paste the above Code into a Standard Module of your Database and save it. Place the cursor anywhere within the Code and press F5 to execute the Code. The LastName Field values of the Employees Table from Northwind.mdb will be displayed in MsgBox control after closing the database. The reading of records is put in a loop to read all the nine records in that table. If you are using a different table with more records then limit the reading cycle by changing the condition in the Do While Not .EOF statement with the support of a Variable like the following code snippet.

With rst
msg = ""
X=1
Do While X < 10
    If Not.EOF then
        msg = msg & ![LastName] & vbCr
       .MoveNext
    End If

    X=X+1
Loop
   .Close
End With

The VBA Code.

The reading statements are placed within an If . . .Then Statement so that the program will cycle through the Loop and terminate normally without running into Error if you have less than 9 records in your Table. The last three statements release the Memory occupied by the Objects.

The first line sets a reference to the Workspace(0) Object and the second line opens the Northwind.mdb Database within the same workspace. Even though this is not visible we can visualize now that there is a partner database within our own Workspace, side by side. The location of the database shown above is for the MSAccess2003 Version. Other Versions may have some difference in location addresses after the \Microsoft Office\ part, but it will be in the \Samples\ Folder. You may find the correct location of your Version of this file and change the Pathname given above.

Next, we will see how to open a dBase File directly and work with it.

Share:

Linking with IBM AS400 Tables

Introduction.

We can convert IBM iSeries (AS400) DB2 Table into dBase Format, download, and Link or Import into MS-Access Databases. The downloading procedure must be created and run from AS400 Menus. If it requires several steps before the output file is transferred to the local drive, then it can be automated with Macro Scripts. The keystrokes can be recorded and modified in such a way that the target file goes to a specific location on the Local Machine with a predefined name that remains linked with the Microsoft Access Database.

If you have sufficient Access Privileges to iSeries (AS400) Main Frame Tables you can Link them directly into your MS-Access Database. We are going to look into this method with ODBC based procedure shortly.

Normally, Reports are generated from AS400 and provided to Users as Hard Copies, or converted into the Report Spool File in Text Form, if Soft Copy is requested for. We can download this File either in Text form or upload it into Microsoft Excel (may not Parse the data correctly into Number or Date etc.) with iSeries Report Down-Loader Program. AS400 tables also can be downloaded directly into Microsoft Excel and in this process, if the number of lines is more than 65535 (the limitation of Microsoft Excel Worksheet) it will create more than one Worksheet automatically to accommodate all the data in Excel File.

Linking to IBM iSeries DB2 Tables.

Let us review the steps for Linking IBM iSeries DB2 Tables in MS-Access Database. The example images are created from the Windows2000 Workstation.

Creating ODBC System DSN.

  1. Select Start Menu - - > Settings - - > Control Panel - - > Administrative Tools - -> double-Click on Data Sources (ODBC).

    The ODBC Data Source Administrator Settings will be displayed. See the Image given below. The Following Steps will walk you through the procedure:

  2. Select System DSN Tab on the ODBC Data Source Administrator.

  3. Click Add . . . Button to display a list of Data Source Drivers.

  4. Select Client Access ODBC Driver (32-bit) from the displayed list in the Create New Data Source Control and Click Finish.

  5. Type a name in the Data Source name Control. I have inserted the name myData as Data Source Name. We have to look for this name when we attempt to link the Table to MS-Access.

  6. Click on the Server Tab.

  7. Type the specific iSeries Folder Name where your data table resides in the Library List Control. If more than one Library File is there, then separate them with Comas.

  8. Put the checkmark on the Read-Only (Select statements only) option under Connection Type, to ensure that we have no intention to modify the data in iSeries Table.
  9. Click Apply followed by OK Button. The System Data Source Name myData appears in the System DSN Tab. See the image below.

  10. Click OK to close the ODBC Configuration Main Control (the Apply button remains disabled in this case).

Linking to MS-Access Database.

  1. Open your MS-Access Database.
  2. Select File - -> Get External Data - - > Link Table or Import Option.
  3. Select ODBC Databases in the Files of Type control in the Common Dialog Control and Click Link (or Import) Button as the case may be.
  4. Select Machine Data Source Tab on the ODBC Control and find the Data Source Name myData that you have created, select it, and click OK.

    You will be prompted for AS400 User-ID and password. Key-in your User ID, Password, and click OK.

    A-List will open up showing all the Table Names available in the AS400 iSeries Machine Prefixed with the Library Name followed by a period.

  5. Select the Table(s) to Link and Click OK.

    The Fields of the selected Table will be displayed suggesting to highlight one or more fields for indexing if needed.

  6. Highlight the field(s), if you would like to create a Unique Index for the Table, otherwise Click OK without selecting any.

The selected Table will be linked (or Imported as the case may be) into your Database.

The AS400 Login Issue

If the table remains linked, whenever you attempt to use the table after opening your MS-Access Database for the first time it will prompt for the AS400 iSeries UserID and Password and after that, the login is valid for the current Session.

If you don't want this to happen in the middle of some processing steps it is better to invoke the login immediately after opening the Database. To do this, create a Query or Form or Report that uses the linked iSeries Table that opens with an Autoexec Macro or the Form in Startup, or even better create a VBA routine to open the linked table which will invoke the login procedure, and the User is prompted for keying in her User ID and Password at the beginning of the current session itself. This will take care of the rest of the Session.

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