Automatically populate an Access database from a script

I have a script that downloads data from a database into a series of CSV files. After they're downloaded, they must be loaded into an Access database for reporting (I use DoCmd.TransferText, and have a saved text import specification). Every time I run the job that generates the data and downloads into CSV, I usually need to load into a fresh copy of the unpopulated version of the Access database. Is there a way to automate this in a batch script?

In short, I need to be able to:

Upvotes: 1

Views: 4804

Answers (1)

HansUp
HansUp

Reputation: 97101

I think you can use VBScript to do what you need.

  • copy the unpopulated Access file to a new file with the timestamp in the name

    FileSystemObject.CopyFile "c:\somefolder\template.mdb", "c:\dest\new.mdb"

See CopyFile Method.

  • load certain CSV files that match a pattern (such as "data_for_reporting_2_20111024_135142.csv") in the directory into the Access file.

You can examine the Files Collection of your CSV folder, determine which of those file names match your target pattern, then run DoCmd.TransferText with each matching file name.

You would run DoCmd.TransferText from an Access application instance:

Option Explicit
Dim appAccess
Dim strMdb
Const cstrFolder = "c:\dest\"

strMdb = "new.mdb"

Set appAccess = CreateObject("Access.Application")
appAccess.OpenCurrentDatabase cstrFolder & strMdb, False

So, do the Transfertext from that instance variable:

appAccess.DoCmd.TransferText [your options]

Edit: This would be faster for me to create and test in VBA. So I think I would use that instead of VBScript.

Create a function, SnarfCSV, in a standard module in your template MDB. Then create a macro, mcrSnarfCSV, with the SnarfCSV function as its runcode action. Then after you copy the template MDB to the new MDB, open the new one with the /x command line switch to run the macro.

"Path to MSACCESS.EXE" "Path to your db file" /x mcrSnarfCSV

Upvotes: 2

Related Questions