I have a bunch of csv files that I import via VBA into tables in Access. I also have a schema.ini file in the same directory as the csv files that I am importing. Despite fields
There are essentially two ways to pre-set the data columns for text file (.txt, .csv, .tab) imports into an Access database, both of which use different VBA methods.
1. Specifications object (saved within the database)
Here, you use DoCmd.TransferText where one of the arguments is an optional specification name (no extension or path).
DoCmd.TransferText(TransferType, SpecificationName, TableName, FileName,
HasFieldNames, HTMLTableName, CodePage)
To create this specification object, you need to manually import an example text file just once, walk through the wizard and just before last section to finish, click the Advanced button which summarizes all items you just specified --field names, lengths, data types, etc. Go ahead and save that entire summary file by clicking Save As on the dialog window and remember the name you give it which is the specification argument in the above.
In fact, once specs is saved, you can cancel the wizard altogether. Import/Export specs are stored in the queryable Access system table, MSysIMEXSpecs, and can be used and reused even overwritten (via wizard again) for the life of the .accdb file. In fact, you can even import into other databases (clicking advanced in External Data wizard).
2. Schema.ini file (saved outside the database)
Here, the text file behaves as an external table since it contains schema which can be linked to Access or opened via a recordset as outlined on Microsoft.com. Now a workaround is needed since this external file does not automate with an import method. Below is a modification of the linked table option where a local table is created through a Make-Table query (carrying all schema and structure and data). Afterwards, the linked table is destroyed (not the table itself just the link). Adjust this into your application, possibly in a button OnClick or form OnOpen events or called from a VBA module via an AutoExec macro (when db first opens).
Function LinkSchema()
Dim db As DATABASE, tbl As TableDef
Set db = CurrentDb()
Set tbl = db.CreateTableDef("Linked Text")
tbl.Connect = "Text;DATABASE=c:\my documents;TABLE=csvFile_linked"
tbl.SourceTableName = "csvFile.csv"
db.TableDefs.Append tbl
db.TableDefs.Refresh
db.Execute "SELECT * INTO csvFile_local FROM csvFile_linked", dbFailOnError
db.TableDefs.Delete("csvFile_linked")
Set tbl = Nothing
Set db = Nothing
End Function
As described above, I personally never use the schema.ini file which might even be an outmoded legacy approach as Microsoft support is not up to date. Specs provide a fluid flexibility in that they work integrally with import/export procedures. Plus, they are saved directly in database without needing to manage them externally.