I want to be able to take a csv file like this one http://ichart.yahoo.com/table.csv?s=^GSPC, which would be located in the workbook folder and make it as a table named GSPC inside an already existing blank MS Access database. The blank database file would be located in the same folder and named tblImport.accdb. I have looked at many forum threads and found nothing simple enough for a noob like me. I'm very happy for any kind of help.
1 Answer
The easiest way to import CSV into Access is to use DoCmd.TransferText from within an Access application session.
But you want to use Excel VBA. In that case, if your MS Office installation includes Access (MSACCESS.EXE), you can use Excel VBA to automate Access and still make use of DoCmd.TransferText for easy CSV import.
I tested this module in Excel 2007. It creates the GSPC table and stores the data from table.csv in that table. If the table already exists, TransferText will simply append the CSV data. You can execute DELETE FROM GSPC before running TransferText so the table will contain only the latest CSV data.
This may look a bit intimidating considering you said you're a noob. However much of the following is comments I added to guide you. The actual "guts" of that procedure is fairly short and simple.
Option Explicit
Public Sub ImportCsvToAccess()
Const cstrCsvFile As String = "table.csv"
Const cstrDbFile As String = "tblImport.accdb"
Const cstrTable As String = "GSPC"
Dim strFolder As String
'* early binding *'
' requires reference to Microsoft Access <version> Object Library
'Dim objAccess As Access.Application
'Set objAccess = New Access.Application
'* late binding *'
' no reference required
Dim objAccess As Object
Set objAccess = CreateObject("Access.Application")
' this is useful during development
' in production, you may prefer to hide it (Visible = False)
objAccess.Visible = True
strFolder = ActiveWorkbook.Path & Chr(92)
'Debug.Print strFolder
objAccess.OpenCurrentDatabase strFolder & cstrDbFile, _
Exclusive:=True
'* early binding *'
'objAccess.DoCmd.TransferText _
' TransferType:=acImportDelim, _
' TableName:=cstrTable, _
' Filename:=strFolder & cstrCsvFile, _
' HasFieldNames:=True
'* late binding *'
' acImportDelim = 0
objAccess.DoCmd.TransferText _
TransferType:=0, _
TableName:=cstrTable, _
Filename:=strFolder & cstrCsvFile, _
HasFieldNames:=True
objAccess.Quit
Set objAccess = Nothing
End Sub
Createto make a table and stackoverflow.com/questions/9564908/… to see how CSVs can be opened. Also, if you plan on manipulating the data after then look into recordsets.DoCmd.TransferTextfrom Access VBA. It can create the Access table for you and save the CSV data in that table. msdn.microsoft.com/en-us/library/office/…