Thursday, September 10, 2009

CSV2MDB in VBScript

Thought I would share the following VBScript, which can be used to automate the transfer of a CSV to an MDB database automatically (columns need to be hardcoded however).

It might not be of any use to much people, but it's out there now :)

'Option Explicit
Dim strConnection, conn, strConnection2, conn2, objResultsCSV, objResultSQL, strSQL
'
' Open connection to the CSV
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\data\;Extended Properties=""text;HDR=YES;FMT=CSVDelimited"""
Set conn = CreateObject("ADODB.Connection")
conn.Open strConnection
'
' Do Query on the CSV
Set objResultsCSV = CreateObject("ADODB.Recordset")
strSQL = "SELECT * FROM test.csv"
objResultsCSV.open strSQL, conn, 3,3
'
' Open connection to the MDB
strConnection2 = "PROVIDER=MSDASQL;DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\data\Test.mdb;UID=admin;PWD=;"
Set conn2 = CreateObject("ADODB.Connection")
conn2.Open strConnection2
'
' Loop through each line of the CSV
Do Until objResultsCSV.EOF
' Insert SQL
strSQL = "INSERT INTO example (Column1, Column2, Column3, Column4) VALUES ('" & objResultsCSV(0) & "','" & objResultsCSV(1) & "','" & objResultsCSV(2) & "','" & objResultsCSV(3) & "');"
conn2.execute strSQL
objResultsCSV.MoveNext
Loop
'
'Close Connections
objResultsCSV.Close
Set objResultsCSV = Nothing
conn.Close
Set conn = Nothing
conn2.Close
Set conn2 = Nothing

No comments:

Post a Comment