<body><script type="text/javascript"> function setAttributeOnload(object, attribute, val) { if(window.addEventListener) { window.addEventListener("load", function(){ object[attribute] = val; }, false); } else { window.attachEvent('onload', function(){ object[attribute] = val; }); } } </script> <iframe src="http://www.blogger.com/navbar.g?targetBlogID=34083602&amp;blogName=LEARN+MS-ACCESS+TIPS+AND+TRICKS&amp;publishMode=PUBLISH_MODE_FTP&amp;navbarType=BLUE&amp;layoutType=CLASSIC&amp;searchRoot=http%3A%2F%2Fblogsearch.google.com%2F&amp;blogLocale=en_US&amp;homepageUrl=http%3A%2F%2Fwww.msaccesstips.com%2F" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" height="30px" width="100%" id="navbar-iframe" allowtransparency="true" title="Blogger Navigation and Search"></iframe> <div></div>
www.msaccesstips.com

LEARN MS-ACCESS TIPS AND TRICKS


International Response Fund

LEARN MS-ACCESS TIPS AND TRICKS

↑ Grab this Headline Animator

Your Ad Here
Sunday, September 14, 2008

Link External Tables with VBA

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 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.


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 with the Source Table Name.


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


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 to print five records of Orders table from 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 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.:



  2. 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


  3. Excel Range Name BranchNames will be used as Table location. The first line is same as above for this example also.




StumbleUpon Toolbar



Column Chart and VBA
Working with Chart Object in VBA
Linking IBM AS400 Tables
Repairing Combacting Database with VBA
Database Open Close Event Alerts

Labels:

4 Comments:

Anonymous Anonymous said…

Excellent. Thanks for posting this. Very helpful to me. Tom in Minneapolis.

December 23, 2008 3:42 PM  
Anonymous Anonymous said…

THANK YOU! This sentence resolved a lot of frustration: "The $ symbol is necessary with the (Excel) Worksheet name." Much appreciated.

January 25, 2009 12:59 AM  
Anonymous Anonymous said…

I linked a table to an Excel spreadsheet. Then when the Excel spreadsheet is changed, an Access query/macro updates the table (update query). However, when creating the same spreadsheet (basically a new Excel speadsheet because the values are different) and running the query/macro again which updates the table again, all the values of the previous changes are wiped out. How can I keep the previous changes or replace the previous values when the unique ID is the same? Should I name each Excel spreadsheet a different name each time?

August 25, 2009 9:01 PM  
Blogger a.p.r. pillai said…

When you Link an Excel Worksheet with specific Sheet Name (or a Named Range) from a WorkBook MS-Access looks for this specific names for maintaining the link correctly. Even if you replace it with a different Workbook with the same Worksheet Name, Workbook Name and earlier data structure but with fresh data the link to access remains intact. You can even copy and paste the data into the earlier worksheet area replacing old data. You don't have to change the name of the worksheet/workbook etc.

Now the Question of updating data on the table. Here there is something not clear to me from what you have stated above. If you are trying to update only certain records of the table while leaving others, which were updated last time untouched, then you have to device a method to identify records for updating into the table and to leave others untouched.

For example: You can introduce a Date field in the Access Table and update this field with the current date while updating data from excel table. Next time you can setup criteria to exclude these records based on the last update date and update others etc.

In either case it is better to create a Make-Table Query, to create a copy of the Access Table (Backup), and add it to the Macro before the update Query line. So that if you find that something went wrong then you can restore the data from this copy of the Table.

You may create Queries on Linked Excel Table and on Access Table on UniqueIDs (as you have stated) and link them in a common query on UniqueID and check the output records or count of records through VBA (=DCount("*","QueryName") to check whether any matching records are there in both tables which likely to overwrite the earlier updated values before actually running the update Query.

Regards,
a.p.r. pillai

August 26, 2009 8:13 PM  

Post a Comment

Note:Comments subject to Review by Blog Author before displaying.

Links to this post:

Create a Link

<< Home


Creative Commons License
Learn MS-Access Tips and Tricks by msaccesstips.com is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 2.5 India License.



This Page is best viewed with 1280 x 1024 Resolution

   FEATURED LINKS
SITEMAP
Command Button Animation
3D Headings on Forms
MsgBox & Office Assistant
Reminder Ticker
MS-Access & E-Mails
Automated E-Mail Alerts
MsgBox with Options Menu
Colorful Command Buttons
Configure Lotus Notes
Alerts through Network
Running this site has become a costly affair as the revenue from Ads is not sufficient to support it. If you find these pages informative & useful and would like to extend a helping hand, then please do it here.





Link Back to us with this Button

Learn MS-Access

Copy and Paste this HTML Code in your Webpage


Add to Technorati Favorites

Programming Blogs - Blog Catalog Blog Directory
Powered by FeedBurner
Add to Google

Software
Computers blogs
TopOfBlogs




AddMe - Search Engine Optimization Submit Your Site Free!
Go BlogZ Ave Blogs
eBlogzilla Changing LINKS
LS Blogs Blogarama
blog search directory BlogUniverse
Find Blogs in Directory RSS Directory
blogskinny.com ShowcaseBlogs.com
Amfibi

Search Engine Optimization and SEO Tools
Dmegs Web Directory Takeaway for Sale Businesses For Sale
Free Submission Directory Free site submission

Free Listing
 





Free Page Rank Checker

AddThis Social Bookmark Button

Enter your email address:

Delivered by FeedBurner



Top Blogs


Microsoft Access is the Jewell among MS-Office suite of Applications. Its Security features are excellent and works fine in Network environment. MS-Access can link/upload data from any Data Source. Applications that you design should be user-friendly and visually pleasing too. Here I would like to share my experience in Microsoft Access Programming with you and I am sure that you will find them interesting too.

My Photo
Name: Ramachandran Pillai
Location: Cochin, India

I am not an Access Guru and not through MS-Access yet. More to learn and I don’t think that aspect has any end because others have their own style of using this tool. We can learn lot more tricks, other than what we already know, from others too. My programming skills in COBOL, BASIC, Turbo-C, dBase, FoxPro, Visual Basic & Basic HTML attained through self-learning. I wrote my first COBOL Program in 1975 for ICL1901, 3rd Generation Main Frame Computer. Worked as a Computer Operator (NCR VRX8555 Mainframe Machine upto 1990) with M/s. Y.B.A. Kanoo, Saudi Arabia. Started using MS-Access Ver.2 in 1996, when dBase III+ and Foxbase (later version Foxpro) were my favorite DBMS. During Last 13 Year period I have developed more than 45 In-House Applications (medium & small) under MS-Access for our Organization, a leading Automotive Company in Oman. All the Applications are fully Secured and runs under Windows Network. It is my pleasure to share my experience with others. Anything interesting that you would like to share with me, please do. My E-mail Address: aprpillai@msaccesstips.com


If you need a Demo of any of the Topic explained here, send me an E-mail to: aprpillai@msaccesstips.com
with the Topic Description, I shall try to send a sample database to you.


Access Tips | Email | Reports | Report Tricks | Graphs | Forms | Menus | Animation | Security | Internet | How TOs | Linking | Query | Progress Meter | Alerts | Process Tips | Access Functions |




Site Designed by:www.msaccesstips.com