Importing Multiple CSV Files into Microsoft Access 2016 - csv

I have multiple very similar CSV files saved in the same directory which I want to import into Access in one go. I want them to all go to one table.
I did some research, taught myself some VBA basics and ended up with this script:
Public Function Import()
Dim strPathFile As String, strFile As String, strPath As String
Dim strTable As String
Dim blnHasFieldNames As Boolean
blnHasFieldNames = True
strPath = "C:\Downloads\models"
strTable = "ModelData"
strFile = Dir(strPath & "*.csv")
Do While Len(strFile) > 0
strPathFile = strPath & strFile
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
strTable, strPathFile, blnHasFieldNames
strFile = Dir()
Loop
End Function
Trying to run the macro doesn't do anything and I'm stuck where to move forward from here.
I followed the same guide to running a macro in this quick minute long video: https://www.youtube.com/watch?v=mXdn7ca2BX4
I'm hoping I just missed a little step somewhere...
Also, I think I need to import each column in text format as one is not returning date/time data correctly.
I have tried to follow some similar questions on here however I do not really understand VBA coding :/
Any help would be great! thanks!

For CSV file files you have to use DoCmd.TransferText:
DoCmd.TransferText TransferType:=acImportDelim, _
TableName:=strTable, _
FileName:=strPathFile, _
HasFieldNames:=True

Related

Import Multiple Csvs into Single Table

I'm trying to use the code below to import multiple csvs into one table. For some reason it imports all csvs but creates a separate table for each instead of importing into the UKR table.
I'm using Access 2016 and UKR is a blank table with no field names or data.
Can anyone see what the issue is?
Thanks
Option Compare Database
Option Explicit
Function DoImport()
Dim strPathFile As String
Dim strFile As String
Dim strPath As String
Dim strTable As String
Dim blnHasFieldNames As Boolean
blnHasFieldNames = True
strPath = "C:\UKR\"
strTable = "UKR"
strFile = Dir(strPath & "*.csv")
Do While Len(strFile) > 0
strTable = Left(strFile, Len(strFile) - 4)
strPathFile = strPath & strFile
DoCmd.TransferText acImportDelim, , strTable, strPathFile, blnHasFieldNames
strFile = Dir()
Loop
MsgBox "done"
End Function
Because code is resetting the destination table within the loop. Remove line
strTable = Left(strFile, Len(strFile) - 4)

importing multiple *.csv files into access - every file into separate table

I have over a thousand files to import into a ACCESS database.
Every file needs to be imported into separate ACCESS table.
It needs to support importing this files every day, because, there are polish stocks prices, so every day, around 08 p.m. I'm downloading a *.zip file containing 1000 *.csv files, and I'll need to import them another time, to get today's prices.
I need to have some settings changed, in order to have my data imported correctly.
next thing is:
advanced settings:
how it looks like.
I don't know how to write these advanced changes in the VBA code.
In EXCEL I could record the macro, and then see the syntax, with the settings I have chosen, but is it possible to do the same in ACCESS ?
There are two codes I've found on the internet.
first:
Function Impo_allExcel()
Dim my_file As String
Dim my_path As String
my_path = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl_csv"
ChDir (my_path) 'why my_path is inside the brackets??
my_file = Dir()
Do While my_file <> "" 'is not empty (<> means not equal to), Excel VBA enters the value into
'this line above doesn't work, when I'm trying to debug it with F8
If my_file Like "*.csv" Then
' this will import ALL the *.CSV files
'(one at a time, but automatically) in this folder.
' Make sure that's what you want.
DoCmd.TransferSpreadsheet acImport, 8, "Contacts_AVDC_NEW", my_path & my_file
' what this above line says ? please explain.
End If
my_file = Dir() ' what it means?
Loop
End Function
second is:
Function Do_Import_from_CSV()
Dim strPathFile As String
Dim strFile As String
Dim strPath As String
Dim strTable As String
Dim blnHasFieldNames As Boolean
' Change this next line to True if the first row in CSV worksheet has field names
blnHasFieldNames = True
' real path to the folder that contains the CSV files
strPath = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl_csv"
' Replace tablename with the real name of the table into which the data are to be imported
strFile = Dir(strPath & "*.csv") 'what this line means?
Do While Len(strFile) > 0
strTable = Left(strFile, Len(strFile) - 4)
strPathFile = strPath & strFile
DoCmd.TransferText acImportDelim, , strTable, strPathFile, blnHasFieldNames
' Uncomment out the next code step if you want to delete the
' EXCEL file after it's been imported
' Kill strPathFile
strFile = Dir() 'what this means?
Loop
End Function
Could U please briefly explain these codes for me,
tell me what is the difference between them,
and how can I incorporate the settings I need into these codes,
or into the one that suits me better.
thanks a lot.

Importing a daily file with variable name into access database

Let me apologize in advance if this question has been posed somewhere and I overlooked it. I've spent multiple days on this and cannot get it to run 100%.
I am trying to import an excel file that gets sent via email every morning into an access database. The file has a date portion that changes every day. The naming follows the same pattern everyday of "FTTQ m-dd-yyyy". The day shown in the file name is for the previous work day, ex. receive email on 8/25 for FTTQ on 8/24. The code below is what I have so far and it will loop through the folder, however when it reaches the correct day it cannot find it. I have tried a couple variations but Access keeps crashing when I try to run it. Ideally I need Access to find the latest date on the file and import it, such as coming in on Monday and getting the file for Friday/Saturday or during the week getting it for the day before. Any help will be greatly appreciated.
Private Sub Button1_Click()
Dim strToday As String
Dim strFilePath as String
Dim strFile as String
strToday = Format(Date, "m-dd-yyyy")
strFilePath = "C:\Users\cole.stratton\Documents\Procurement\FTTQ 'Note:FTTQ is the beginning of the file name
strFile = Dir(strFilePath, "*.xlsx")
Do While strFile <> ""
If Right(strFile,14) = strToday & ".xlsx" Then
DoCmd.TransferSpreadsheet, acImport, "tblTest",strFile, True
End If
strFile = Dir 'Note: I do not understand the point of this line or what it does or supposed to do.
Loop
End Sub
To find the latest existing file, I would change the loop like this:
Dim searchDate As Date
Dim strDate As String
Dim strFilePath As String
Dim strFile As String
Dim i As Long
' Search backwards from today for a file with the date name
For i = 0 To -7 Step -1
searchDate = DateAdd("d", i, Date)
strDate = Format(searchDate, "m-dd-yyyy")
strFilePath = "C:\Users\cole.stratton\Documents\Procurement\FTTQ " & strDate & ".xlsx"
Debug.Print "Looking for: " & strFilePath
' Check if file exists
strFile = Dir(strFilePath)
If strFile <> "" Then
' Note that Dir() only returns the file name, so use strFilePath
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "tblTest", strFilePath, True
' file found, exit loop
Exit For
End If
Next i
***I'm assuming that you have the closing " in your strFilePath line in your actual code. ****
This line looks like the issue...
strFile = Dir(strFilePath, "*.xlsx")
This page will show you the correct syntax for using Dir...http://www.techonthenet.com/excel/formulas/dir.php
strFile = Dir(strFilePath & "*.xlsx") <-- you were putting the file extension in where the attributes were supposed to go.
However, you also need to change your date. If the file will have yesterday's date, not today's...strToday = Format(Date-1, "m-dd-yyyy")
This line...
strFile = Dir
sets your string to the next file name that meets your search criteria.

How do I call a function in Access 2010?

I know this question has been asked over and over, but I can't follow any of the guides I've found.
I'm a total beginner with Access and writing VBA, so I found some code that will help me import A LOT of files into separate tables in Access.
I have tried several variations of putting the code in and calling from a macro or a button...none of them have been successful.
There might be something wrong with the code, but I don't know enough to figure it out. I'm also pretty sure I'm doing something else wrong when trying to call the function. Please help me!
Here's the code:
Option Compare Database
Option Explicit
Function DoImport()
Dim strPathFile As String, strFile As String, strPath As String
Dim strTable As String
Dim blnHasFieldNames As Boolean
' Change this next line to True if the first row in EXCEL worksheet
' has field names
blnHasFieldNames = True
' Replace C:\Documents\ with the real path to the folder that
' contains the EXCEL files
strPath = "C:\Documents and Settings\user\Desktop\folder"
' Replace tablename with the real name of the table into which
' the data are to be imported
strTable = "tablename"
strFile = Dir(strPath & "*.xls")
Do While Len(strFile) > 0
strPathFile = strPath & strFile
strTable = Left(strFile, Len(strFile) - 4)
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
strTable, strPathFile, blnHasFieldNames
' Uncomment out the next code step if you want to delete the
' EXCEL file after it's been imported
' Kill strPathFile
strFile = Dir()
Loop
End Function
To call this procedure it either needs to exist in the current form where the button is or reside in a Module of its own.
Because the function does not return a value or have any arguments to call it you would type the following VBA code in a button's On Click event:
DoImport
If you wish to make sure the code is actually running you can set a breakpoint by pressing F9 on an executable line of code
Or type the word Stop where you want to debug
The code itself will not be very useful until you have made the changes to the literal strings as the code comments suggest
The code itself as it stands is not very reusable so as a next step you should research using arguments so when you call the function at runtime you can supply the folder name and table name et cetera.
The code itself will search a particular folder for Excel files and attempts to import each file into Microsoft Access, using the filename as the table name.
How about creating a new Module and pasting the below code into it. Save it and name it whatever you want.
Public Function DoImport(strPath AS String, strTable AS String, _
blnHasFieldNames AS Boolean, RemoveFile AS Boolean)
Dim strFile As String
strFile = Dir(strPath & "*.xls")
Do While Len(strFile) > 0
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, strTable, _
strPath & strFile, blnHasFieldNames
if RemoveFile Then Kill strPath & strFile
strFile = Dir()
Loop
End Function
Then you can call the function via the following:
DoImport "C:\imports\Excel\", "MyTableName", True, True
This allows you to pass the path, table name, whether the files contain field names and if you want to remove the file after import. That way you don't have to potentially change the code of the function constantly.

MS Access: Import Specification not working through VBA

I have an import specification for csv files which, when I run it on a file through the GUI, works just fine. However, when I run it through VBA, for some reason it forgets that one column is supposed to be a Text column and makes it a Number column instead, thereby causing tons of errors.
My code is below. It works in the sense that everything runs properly, but for some reason the import specification for the CSVs does not run properly. The meaningless case switch is a place holder, as I will need to add more types of reports after I get the first working.
Sub ImportDE(Folder As Object)
Dim db As DAO.Database
Dim names As DAO.Recordset
Dim Files As Object, file As Object, SubFolders As Object, subfolder As Object
Dim ExString As Variant
Dim check As Boolean
Dim FileChange As String
Set db = CurrentDb
On Error Resume Next: db.TableDefs.Delete "tblImport": On Error GoTo 0
db.TableDefs.Refresh
Set names = CurrentDb.OpenRecordset("SELECT Old FROM DENames")
Set Files = Folder.Files
Set SubFolders = Folder.SubFolders
For Each subfolder In SubFolders
ImportDE subfolder
Next
With names
Do While Not .EOF
ExString = .Fields(0)
For Each file In Files
If InStr(file.Type, "Worksheet") > 0 Then
If InStr(file.Path, ExString & ".xls") > 0 Then
DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadsheetType:=acSpreadsheetTypeExcel9, _
TableName:="tblImport_" & ExString, _
filename:=file.Path, _
HasFieldNames:=True, _
Range:="A:CT"
db.TableDefs.Refresh
End If
ElseIf InStr(file.Type, "Comma Separated") > 0 Then
If InStr(file.Path, ExString & ".csv") > 0 Then
Select Case ExString
Case "Usage"
DoCmd.TransferText _
TransferType:=acImportDelim, _
SpecificationName:=UsageCSV, _
TableName:="tblImport_" & ExString, _
filename:=file.Path, _
HasFieldNames:=True
db.TableDefs.Refresh
End Select
End If
End If
Next
.MoveNext
Loop
End With
db.Close: Set db = Nothing
End Sub
Am I missing something obvious? Why doesn't the import spec work properly?
The TransferText SpecificationName parameter is supposed to be a string expression. Since the code does not declare a variable named UsageCSV, I'm guessing that is the literal name of the specification. If that's correct, enclose the name in double quotes.
DoCmd.TransferText _
TransferType:=acImportDelim, _
SpecificationName:="UsageCSV", _
TableName:="tblImport_" & ExString, _
filename:=file.Path, _
HasFieldNames:=True
At the top of your code module After Option Compare Database
Add Option Explicit.
This will require all of your variable to be declared and you will never have this issue again