Import data from an external source through code

C

Chris

Hi All,

We have around 50 txt files that are being imported into access each day.
At the moment it is done manually (file -> get external data -> import ->
etc etc etc.

It is getting imported into an existing table and is the procedure for
importing never changes

Any idea's?
 
J

Jeff Boyce

Chris

One alternative to importing a text document is to add a "pointer"/path to
the document's file location.

Regards

Jeff Boyce
Microsoft Office/Access MVP
 
G

Guest

Are all the files in the same directory?
Are all the files in the same format?
Do all the files get appended to the same table?
Does the data in the files replace data in a table or tables or is the data
appended to existing tables?
 
C

Chris

Are all the files in the same directory? - Yes
Are all the files in the same format? - Yes
Do all the files get appended to the same table? - Yes
Does the data in the files replace data in a table or tables or is the data
appended to existing tables? - The table's data is deleted every day, so
the data will be going into an empty table.
 
G

Guest

Okay, great. You can use the Dir function to set up the loop to do the
imports. First, I would suggest you set up an Import Specification for the
text files. You do that by manually preforming an import. When you get the
import dialog, click on Advanced. There you can define field names, data
types, etc. Once you have everything configured the way you want it, click
on Save As and give it a name. This is the name you will use in your
TransferText method. In addition to your production table, you will need an
intermediate table. This table will recieve data from the text file, then be
used to transfer the data to the production table.

Here is the seguence of events:
1. Delete the data in the production table
2. Delete the data in the intermediate table
3. Import the text file to an intermediate table
4. Run an Append query to append the data to the production table
5. Repeat 2 - 4 for all text files in the folder.

The code will look something like this:

Dim strNextFile as String
Dim strFilePath as String
Dim dbf as Database

dbf = CurrentDb
strPath = "F:\WhereMyFilesAre\"

strNextFile = Dir(strPath & "*.txt") ' If extension is not txt, change
this to match
dbf.Execute("DELETE * FROM MyProductionTable;"), dbFailOnError

Do While strNextFile <> ""
dbf.Execute("DELETE * FROM MyIntermediateTable;"), dbFailOnError
DoCmd.TransferText acImportDelim, ImportSpecName,
"MyIntermediateTable", strPath & strNextFileName, True
dbf.Execute("qappAddToProduction"), dbFailOnError
strNextFile = Dir()
Loop
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top