Importing a daily file with variable name into access database - ms-access

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.

Related

MSAccess VBA to Save a Single Attachment to a Folder

I'm really new to Access so I haven't heard of most of the commands for Access VBA, but I am pretty familiar with Excel VBA.
What I'm trying to do is save the attachment that was just entered into a table through a form. I've been looking at some examples online and trying to get it to work for me but the code is not moving the file to the folder. I do not get a debug error though.
Here is my current code. I know it is set to loop right now, where really I just want the last attachment in the table each time, but I don't know how to get only the last attachment. Either way, this current code doesn't move ANY attachments.
Private Sub cmdAddRecord_Click()
If MsgBox("Adding a new record will save the current form. You will not be able to edit this credit request. Would you like to continue?", vbQuestion + vbYesNo, "Save current record and open new form") = vbYes Then
MkDir "C:\Users\username\Desktop\IC Transfer Back Up Attachments\" & Me.txtRequestID & "-" & "Back Up Attachments" & " " & Format(Date, "MMDDYY")
DoCmd.RunCommand acCmdSaveRecord
Dim SaveFolder As String
SaveFolder = "C:\Users\username\Desktop\IC Transfer Back Up Attachments\" & Me.txtRequestID & "-" & "Back Up Attachments" & " " & Format(Date, "MMDDYY")
Dim rsParent As DAO.Recordset2
Dim rsChild As DAO.Recordset2
Set rsParent = CurrentDb.OpenRecordset("SELECT * FROM tblICTRequested")
Set rsChild = rsParent.Fields("BackUpAttachments").Value
Do Until rsChild.EOF
rsChild.Fields("FileData").SaveToFile SaveFolder
rsChild.MoveNext
Loop
DoCmd.RunCommand acCmdCloseWindow
DoCmd.OpenForm "frmICTRequested"
End If
End Sub
Most of this seems to make sense to me, but I'm not sure what I should put in the .Fields("FileData").SaveToFile line, since I don't have a field named "FileData" but I've tried all my existing fields to no avail.
For reference, here are some of the online links I have reviewed:
https://www.experts-exchange.com/questions/29005769/MS-Access-attachment-file.html
https://msdn.microsoft.com/en-us/library/office/ff191852.aspx
https://access-programmers.co.uk/forums/showthread.php?t=282135
Any tips? Much appreciated!
You're very close. I use a function like this:
Public Function SaveFileToDisk(FileName As String, FileData As DAO.Field2, Optional saveToFolder As String) As String
Dim templatePath As String
If saveToFolder = "" Or Not fso.FolderExists(saveToFolder) Then
saveToFolder = Environ("temp")
End If
templatePath = GetAvailableFileName(FileName, saveToFolder, True) 'A function to create a unique file name
FileData("FileData").SaveToFile templatePath
SaveTemplateToDisk = templatePath
End Function
It gets called like this:
Dim tempPath As String
Dim fileData as DAO.Field2
Dim folderToSaveTo as string
folderToSaveTo = "C:\some\folder"
set fileData = rsParent.Fields("BackUpAttachments")
tempPath = exporter.SaveTemplateToDisk("Name of file.ext", fileData , folderToSaveTo)
The attachment field is kind of like a recordset withing a field.
So with the help of someone, I changed the line:
Set rsParent = CurrentDB.OpenRecordset("SELECT * FROM tblICTRequested")
To:
Set rsParent = CurrentDB.OpenRecordset("SELECT * FROM tblICTRequested WHERE ID =" & Me.txtRequestedID)
This seems to be working perfectly for my purpose! Thank you to everyone who provided information!

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.

Automatic import of CSV files to Access table

I'm trying to set up an automatic process that scans a particular network folder for new CSV files and then appends the data to a table in Access.
A new CSV is placed in the folder everyday and they all have the same naming convention - ClosingPrice_ddmmyy with the date part changing on every file.
What's the most straight forward way to set up such a process?
All suggestions welcome!
Thanks for the reply, Rahul.
I found the following code on another forum that does most of what I want. It imports all the CSVs from within the source folder and adds them to a table within Access. However, in future I just want to add new CSVs that are added to the folder and not all the CSVs every time. Any ideas on how I can change the code to do this?
Thanks,
Sub Import_CSV()
'Modified from WillR - www.willr.info (December 2004)
Const strPath As String = "C:\ImportFolder\" 'Directory Path
Dim strFile As String 'Filename
Dim strFileList() As String 'File Array
Dim intFile As Integer 'File Number
'Loop through the folder & build file list
strFile = Dir(strPath & "*.csv")
While strFile <> ""
'add files to the list
intFile = intFile + 1
ReDim Preserve strFileList(1 To intFile)
strFileList(intFile) = strFile
strFile = Dir()
Wend
'see if any files were found
If intFile = 0 Then
MsgBox "No files found"
Exit Sub
End If
'cycle through the list of files & import to Access
'creating a new table called MyTable
For intFile = 1 To UBound(strFileList)
DoCmd.TransferText acImportDelimi, ImportSpec, _
"Raw Data", strPath & strFileList(intFile), -1
'Check out the TransferSpreadsheet options in the Access
'Visual Basic Help file for a full description & list of
'optional settings
Next
MsgBox UBound(strFileList) & " Files were Imported"
End Sub

Import Specific Files from Folder into Access Table

Background:
I receive a daily sales files that I would like to import into access automatically. They are currently saved to a specific folder with a consistent naming convention. I don't review these files everyday and would like to make the import process a push button procedure. There are other files in the folder that I don't need, so I can't just import the entire file.
File Naming Convention: DAILY.SALES.20160611
(the 20160611 is the Year - 2016, Month - June, and Day 11th)
Help needed:
I can import all the files, but I can't figure out how to specify only those files that begin with "Daily.Sales". Below is the code I have that can import everything without specifying. My assumption is that it has something to do with the path or strFile, but none of the variations that I've tried has worked.
It would be nice if the code could actually check if the file has already been uploaded before uploading it, however, if I have to delete the table after each use and re-upload everything that is still easier.
Dim strFile As String 'Filename
Dim strFileList() As String 'File Array
Dim intFile As Integer 'File Number
Dim filename As String
Dim path As String
DoCmd.SetWarnings False
path = "C:\Desktop\Test\"
Dim objXL As Object
Dim wb As Object
Set objXL = CreateObject("Excel.Application")
strFile = Dir(path & "*.xls")
While strFile <> ""
Set wb = objXL.Workbooks.Open(path & strFile)
If wb.Sheets(1).Range("A1") <> "No Data" And wb.Sheets(1).Range("A1") <> "" Then
'add files to the list
intFile = intFile + 1
ReDim Preserve strFileList(1 To intFile)
strFileList(intFile) = strFile
End If
strFile = Dir()
Debug.Print strFileList(intFile)
wb.Close False
Set wb = Nothing
Wend
'see if any files were found
If intFile = 0 Then
MsgBox "No files found"
Exit Sub
End If
'cycle through the list of files
For intFile = 1 To UBound(strFileList)
filename = path & strFileList(intFile)
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel8, "Stage", filename, False
Call Format_Staging_Table
Call Copy_from_Stage_to_Master
Call Clear_Staging_Table
Next intFile
DoCmd.SetWarnings True
You can ignore the Call pieces, they are to format the data once I get it in...
Thanks for any help or advice that anyone might be able to provide!
Ok, I just answered a question like this 1 minute ago. I think you should take a look at this link.
http://www.accessmvp.com/KDSnell/EXCEL_Import.htm#ImpAllWktsSepTbl
Just modify that to suit your needs... Basically...change the path and folder to match your file name...

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.