First off, this is a compilation of code from various sources and as much as I would like to give credit, I cannot find the originator. My apologies.
Dilemma, I have 5 spreadsheets, all different names, there is one tab on each spreadsheet with the same name as the file and in Access there is a corresponding table name that is the same(keeping it simple.) In the code below, it imports the first worksheets tab data into the corresponding table in Access and prompts me with the message box saying it is done. However, none of the other tables are imported, which makes sense. I am missing a component to call each file versus just one worksheet. FYI, I cannot combine these files into one worksheet, because some of the worksheets have a ton of data. They are all .xlsb files. Am I missing a step?
Function Fnc_ImportData()
Dim strPathFile As String, strFile As String, strPath As String
Dim blnHasFieldNames As Boolean
Dim intWorksheets As Integer
' delete the current data in all 5 tables in Access
DoCmd.OpenQuery "qry_F2F_Alloc_tblDataDelete"
DoCmd.OpenQuery "qry_GDM_USD_tblDataDelete
DoCmd.OpenQuery "qry_GDM_USD_BDGT_tblDataDelete
DoCmd.OpenQuery "qry_IntraHR_Data_tblDataDelete
DoCmd.OpenQuery "qry_IT_ProjectCosts_tblDataDelete
' Replace (1 to #) with the number of worksheets to be imported
' from each EXCEL file
Dim strWorksheets(1 To 5) As String
' Replace (1 to #) with the number of worksheets to be imported
' from each EXCEL file (this code assumes that each worksheet
' with the same name is being imported into a separate table
' for that specific worksheet name)
Dim strTables(1 To 5) As String
' Replace generic worksheet names with the real worksheet names;
' add / delete code lines so that there is one code line for
' each worksheet that is to be imported from each workbook file
' strWorksheets(1) = "GenericWorksheetName1"
strWorksheets(1) = "tbl_F2F_Alloc"
strWorksheets(2) = "tbl_GDM_USD"
strWorksheets(3) = "tbl_GDM_USD_BDGT"
strWorksheets(4) = "tbl_IT_ProjectCosts"
strWorksheets(5) = "tbl_IntraHR_Data"
' Replace generic table names with the real table names
' strTables(1) = "GenericTableName1"
strTables(1) = "tbl_F2F_Alloc"
strTables(2) = "tbl_GDM_USD"
strTables(3) = "tbl_GDM_USD_BDGT"
strTables(4) = "tbl_IT_ProjectCosts"
strTables(5) = "tbl_IntraHR_Data"
' 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 = "\\admpls173m\findata\Functions_Finance\HR Monthly PnL\2-Database\Files\TEST MAIN FILES\"
' Replace # with the number of worksheets to be imported
' from each EXCEL file
' For intWorksheets = 1 To #
For intWorksheets = 1 To 5
strFile = Dir(strPath & "*.xlsb")
Do While Len(strFile) > 0
strPathFile = strPath & strFile
DoCmd.TransferSpreadsheet acImport, _
acSpreadsheetTypeExcel12, strTables(intWorksheets), _
strPathFile, blnHasFieldNames, _
strWorksheets(intWorksheets) & "$"
strFile = Dir()
Loop
Next intWorksheets
DoCmd.SetWarnings True
'Message box telling you the data has been imported into the Tbl_Summary
MsgBox "Access Has Finished Importing the Files." & Chr(13) & "Data Is Ready To Be Reviewed.", vbInformation
Exit_File1_Click:
Exit Function
Err_File1_Click:
MsgBox Err.Description
Resume Exit_File1_Click
End Function
Related
Situation:
I am iterating through an Outlook-Mailbox and downloading all attachments into specific folders. Then I am iterating through the folders and import the CSV-Files into Access.
Problem:
I have the Outlook.MailItem.receiveTime property and the sender's name, which I have got from the File Title. I want to add those two pieces of information to each row of each CSV-File.
Question:
Is there a possibility to add those two columns on import or do I have to open each file and iterate through the content to add them?
Little side question:
Would it be possible to import the files directly from Outlook, meaning, without heaving to save them?
Software and languages I use:
-Access 2013
-Outlook 2013
-VBA
-SQL
Little side Information: I am triggering all of this from an Access Form.
You can loop through all CSV files and import each to a table.
Private Sub Command0_Click()
Const strPath As String = "C:\your_path_here\" '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, , _
"Test", strPath & strFileList(intFile)
'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
If you want to download attachment from Outlook, try this.
Private Sub GetAttachments()
Dim ns As Namespace
Dim Inbox As Outlook.MAPIFolder
Dim Item As Object
Dim Atmt As Outlook.Attachment
Dim FileName As String
Set ns = GetNamespace("MAPI")
Set Inbox = ns.Folders("MailboxName").Folders("Inbox")
If Inbox.Items.Count = 0 Then
MsgBox "There are no messages in the Inbox.", vbInformation, _
"Nothing Found"
Exit Sub
End If
For Each Item In Inbox.Items
For Each Atmt In Item.Attachments
If Atmt.Type = 1 And InStr(Atmt, "xlsx") > 0 Then
FileName = "C:\attachments\" & Atmt.FileName
Atmt.SaveAsFile FileName
End If
Next Atmt
Next Item
End Sub
Set a reference to MS Outlook and remember, the "MailboxName" is your email address.
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.
Overall Goal:
Pull all files from folder > format files in staging table > copy staging table to master table > kill staging table > rinse and repeat until all files have been taken from folder, formatted and put into the master table.
Issue:
I have apparently not taken into account that some of the files sent to me will have blank worksheets (rather they may have a value that says "No Data" in cell A1). When my macro hits the "No Data" or blank sheet I get a Null error (94).
What I've tried:
strF1Data = Nz(!ref_val)
strF1Data = Nz(!ref_val,"")
Suspicions:
I think I can update the SQL UPDATE line to allow Nulls, but I feel like a more efficient solution would be to skip if null. However I have tried modifying the Do Until statement and had no luck...
Possibly Worth Mentioning:
The files have multiple worksheets. I learned this the hard way in finding this error on a random worksheet between several other worksheets that did have data.
Code: (to help save some space, I'm only giving the call files bit and formatting piece, I don't think the other pieces will be of any use. However if you would like them then let me know.)
The overall macro (see next code sections for piece with error):
Sub Pull_File_into_Staging_Table()
'Process:
'1 - Loop through all files saved to specified folder making an internal list of the files
'2 - Paste one files content to staging table at a time
'3 - Format the information in the staging table
'4 - Copy formatted staging table to 1Compare Table (master table)
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:\Users\USER\Desktop\Test\"
Dim rs As DAO.Recordset ' Moved from below
Dim db As DAO.Database
Set db = CurrentDb
'Loop through the folder & build file list
strFile = Dir(path & "*.xls")
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
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
End Sub
The piece with the issue:
Sub Format_Staging_Table()
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:\Users\USER\Desktop\Test\"
Dim rs As DAO.Recordset ' Moved from below
Dim db As DAO.Database
Set db = CurrentDb
CurrentDb.Execute ("ALTER TABLE Stage ADD COLUMN UPC Text, SR_Profit_Center Text, SR_Super_Label Text, SAP_Profit_Center Text, SAP_Super_Label Text;")
CurrentDb.TableDefs("Stage").Fields("F1").Name = "ref_val"
Dim ref_val As String
Set rs = db.OpenRecordset("SELECT TOP 1 ref_val FROM Stage;", dbOpenDynaset)
ref_val = rs.Fields(0).Value
rs.Close
db.Execute "DELETE FROM [Stage] WHERE ref_val = '" & ref_val & "';"
Const YOUR_TABLE_NAME As String = "Stage"
Dim SQL_UPDATE_DATA As String
SQL_UPDATE_DATA = "SELECT *, ';' & '" & ref_val & "' FROM [" & YOUR_TABLE_NAME & "] WHERE SR_Profit_Center Is Null"
Dim strF1Data As String
Dim varData As Variant
Set rs = CurrentDb.OpenRecordset(SQL_UPDATE_DATA)
With rs
Do Until .EOF
strF1Data = !ref_val
varData = Split(strF1Data, ";")
If UBound(varData) = 4 Then
.Edit
!ref_val = ref_val
!UPC = varData(0)
!SR_Profit_Center = varData(1)
!SR_Super_Label = varData(2)
!SAP_Profit_Center = varData(3)
!SAP_Super_Label = varData(4)
.Update
End If
.MoveNext
Loop
.Close
End With
Set rs = Nothing
End Sub
Also I'm aware of the extra variable pieces, I will clean it up once I get it working.
File Examples:
Working File:
CE16041901
00791558441123;US1K100017;CGR;US1K100001;UNKNOW
00791558442328;US1K100017;CGR;US1K100001;UNKNOW
00791558440720;US1K100017;CGR;US1K100001;UNKNOW
00791558444629;US1K100017;CGR;US1K100001;UNKNOW
00791558440522;US1K100017;CGR;US1K100001;UNKNOW
00791558443325;US1K100017;CGR;US1K100001;UNKNOW
Not Working File:
CE16042001
00791558334128;US1K100017;CGR;US1K100001;UNKNOW
00791558159523;US1K100017;CGR;US1K100001;UNKNOW
00602547736604;US1A100018;UR;US1A100018;US-RU
I appreciate any help. I ran with this as far as I could, but I am still very much a novice when it comes to access and vb. If you need more information or clarification please let me know and I'll do my best to provide/explain.
No need to touch the staging table functions. Simply conditionally populate the strFileList array depending if Excel workbooks' first sheet contains No Data or empty cell. Recall Access VBA has complete access to all Excel objects via COM interface or Excel VBA reference and so can iteratively open workbooks. Hence, adjust your While/Wend loop accordingly:
Sub Pull_File_into_Staging_Table()
'...same code...
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()
wb.Close False
Set wb = Nothing
Wend
'...
I have a query "myQuery" that returns more than 65,000 records, and as such, cannot be exported to one .xlsx file.
I'm attempting to break up this output to multiple files.
I'm still very much a beginner with VBA, but I've put the following together as best I can from research. This code is intended to iterate through the queried data, then output a new file for each 65,000 records.
Private Sub btnfrm1export_Click()
Dim outputFileName As String
Dim dlgOpen As FileDialog
Dim numFiles As Integer
Dim rs As String
Dim numr As Integer
Dim sql As String
Dim rec As Recordset
'Allows user to pick destination for files and gives value to sItem.
Set dlgOpen = Application.FileDialog(msoFileDialogFolderPicker)
With dlgOpen
.Title = "Select a Folder"
.AllowMultiSelect = False
If .Show <> -1 Then
sItem = .SelectedItems(1)
End If
End With
'Counts the records in myQuery to give the number of files needed to numFiles, assuming 60,000 records per file.
Set rec = CurrentDb.OpenRecordset("myQuery")
numFiles = Round(rec.RecordCount / 60000, 0)
numr = 1
' Changes the SQL of the query _vba in the current Database to select 60000 records from myQuery
rs = "SELECT TOP 60000 myQuery.* FROM myQuery"
CurrentDb.QueryDefs("_vba").sql = rs
'Defines SQL for clearing top 60000 (used in the following loop).
sql = "DELETE TOP 60000 myQuery.* FROM myQuery"
'Loops once to create each file needed
Do While numFiles > 0
'Sets a file name based on the destination folder, the file number numr, and information from a combobutton cbo1 on Form frm1.
outputFileName = sItem & "\" & Forms!frm1!cbo1 & "_Report_Pt" & numr & "_" & Format(Date, "yyyyMMdd") & ".xlsx"
'Outputs top 60000 of myQuery records to an excel file.
DoCmd.OutputTo acOutputQuery, "_vba", acFormatXLSX, outputFileName
numFiles = numFiles - 1
numr = numr + 1
'Deletes top 60000 from myQuery.
CurrentDb.Execute sql
Loop
End Sub
However, I'm getting:
Run-time error '2302': Microsoft Access can't save the output data to the file you've selected.
at DoCmd.OutputTo acOutputQuery, "_vba", acFormatXLSX, outputFileName
I do need this to be automated in vba and without pop-ups, etc. Any suggestions to make my code more efficient and proper is appreciated, but the REAL question is how to eliminate the error with DoCmd.OutputTo or make this work.
Thanks for any and all help!
Although the subject line concerns trying to output multiple Excel files, the real issue is trying to create an Excel file from an Access table or query which contains more than 65,000 rows - by using VBA. If VBA is NOT a requirement, then you can export a query or table by right-clicking on the object name, selecting export, then Excel. DO NOT check the box for 'Export data with formatting...' and it will work.
The code shown below was found at: http://www.myengineeringworld.net/2013/01/export-large-access-tablequery-to-excel.html (Created By Christos Samaras) and will properly export a large table/query to Excel
Option Compare Database
Option Explicit
Sub Test()
'Change the names according to your own needs.
DataToExcel "Sample_Table", "Optional Workbook Path", "Optional Target Sheet Name"
'Just showing that the operation finished.
MsgBox "Data export finished successfully!", vbInformation, "Done"
End Sub
Function DataToExcel(strSourceName As String, Optional strWorkbookPath As String, Optional strTargetSheetName As String)
'Use this function to export a large table/query from your database to a new Excel workbook.
'You can also specify the name of the worksheet target.
'strSourceName is the name of the table/query you want to export to Excel.
'strWorkbookPath is the path of the workbook you want to export the data.
'strTargetSheetName is the desired name of the target sheet.
'By Christos Samaras
'http://www.myengineeringworld.net
Dim rst As DAO.Recordset
Dim excelApp As Object
Dim Wbk As Object
Dim sht As Object
Dim fldHeadings As DAO.Field
'Set the desired recordset (table/query).
Set rst = CurrentDb.OpenRecordset(strSourceName)
'Create a new Excel instance.
Set excelApp = CreateObject("Excel.Application")
On Error Resume Next
'Try to open the specified workbook. If there is no workbook specified
'(or if it cannot be opened) create a new one and rename the target sheet.
Set Wbk = excelApp.Workbooks.Open(strWorkbookPath)
If Err.Number <> 0 Or Len(strWorkbookPath) = 0 Then
Set Wbk = excelApp.Workbooks.Add
Set sht = Wbk.Worksheets("Sheet1")
If Len(strTargetSheetName) > 0 Then
sht.Name = Left(strTargetSheetName, 34)
End If
End If
'If the specified workbook has been opened correctly, then in order to avoid
'problems with other sheets that might contain, a new sheet is added and is
'being renamed according to the strTargetSheetName.
Set sht = Wbk.Worksheets.Add
If Len(strTargetSheetName) > 0 Then
sht.Name = Left(strTargetSheetName, 34)
End If
On Error GoTo 0
excelApp.Visible = True
On Error GoTo Errorhandler
'Write the headings in the target sheet.
For Each fldHeadings In rst.Fields
excelApp.ActiveCell = fldHeadings.Name
excelApp.ActiveCell.Offset(0, 1).Select
Next
'Copy the data in the target sheet.
rst.MoveFirst
sht.Range("A2").CopyFromRecordset rst
sht.Range("1:1").Select
'Format the headings of the target sheet.
excelApp.Selection.Font.Bold = True
With excelApp.Selection
.HorizontalAlignment = -4108 '= xlCenter in Excel.
.VerticalAlignment = -4108 '= xlCenter in Excel.
.WrapText = False
With .Font
.Name = "Arial"
.Size = 11
End With
End With
'Adjusting the columns width.
excelApp.ActiveSheet.Cells.EntireColumn.AutoFit
'Freeze the first row - headings.
With excelApp.ActiveWindow
.FreezePanes = False
.ScrollRow = 1
.ScrollColumn = 1
End With
sht.Rows("2:2").Select
excelApp.ActiveWindow.FreezePanes = True
'Change the tab color of the target sheet.
With sht
.Tab.Color = RGB(255, 0, 0)
.Range("A1").Select
End With
'Close the recordset.
rst.Close
Set rst = Nothing
Exit Function
Errorhandler:
DoCmd.SetWarnings True
MsgBox Err.Description, vbExclamation, Err.Number
Exit Function
End Function
I have researched the code for this online for weeks but still cannot find what I need so any help will be greatly appreciated:
I need to:
1) Import the first CSV in "C:\Documents" and create a table called "Data" with import specs I have already created.
2) Create and export all fields in a (SELECT?) query (Sport = Football, Event = Match Odds) to an excel binary file called "Match Odds 001"
I then wish to delete the data contained in this query from the Table "Data".
3) Repeat step 2) two hundred times with different Events exporting each query to an excel binary file with the name "(Event) 001" then deleting that query data from the table.
4) After all queries have run and been deleted, any remaining data in the table will be exported to an excel binary file named "Misc 001" and then this data deleted from the Table "Data" (or maybe even delete the Table "Data" completely.)
5) Repeat from 1) importing the 2nd CSV file from "C:\Documents" and exporting queries to Excel Binary files named "(Event) 002" so as not to replace the previous files.
This would continue until all CSVs have been imported and split.
As there are 200 queries I'd prefer to create them in VBA code.
I have just started using VBA in Access and so far have found code which will import all csv files in a folder so I am hoping to insert code to create, export then delete the queries.
Any help on the vba coding required is hugely appreciated.
.
.
UPDATE: With massive thanks to Mike I now have the following code but a few small issues have surfaced.
1) How can I compact the Database to reduce the filesize after the "DoCmd.RunSQL "DROP TABLE Data"" command?
I wish to repeatedly import 500MB CSV's then delete them so after I import and drop the first then import the second the filesize becomes 1GB and is increasing.
2) How difficult is it to include a second column in the Events Table so that my SELECT query becomes WHERE Event=Event & Selection=Selection and to combine both these fields to create the filename?
3) The Events Table used to create the Queries and file names sometimes contains characters that cannot be used in file names, for Example "/" & "?". Can these be easily dropped to create the filenames or might it be better to add a further column to the Events Table which would contain the filename to be used (ie a combination of Event and Selection but with the disallowed characters removed)
If I can solve these issues I will have the perfect code for my needs, again with all credit to Mike.
Sub ImportAndSplit()
Dim fileCounter As String
Dim rs As New ADODB.Recordset
Dim sql As String
Dim qdf As QueryDef
Dim file As String
Const strPath As String = "C:\Users\Robbie\Documents\Data\" 'Directory Path
Dim strFile As String 'Filename
Dim strFileList() As String 'File Array
Dim intFile As Integer 'File Number
strFile = Dir(strPath & "*.csv") 'Loop through the folder & build file list
While strFile <> ""
intFile = intFile + 1 'add files to the list
ReDim Preserve strFileList(1 To intFile)
strFileList(intFile) = strFile
strFile = Dir()
Wend
If intFile = 0 Then 'see if any files were found
MsgBox "No files found"
Exit Sub
End If
DoCmd.SetWarnings False
Set qdf = CurrentDb.QueryDefs("Export")
sql = "SELECT Event FROM Events"
rs.Open sql, CurrentProject.Connection, adOpenStatic, adLockReadOnly
For intFile = 1 To UBound(strFileList) 'cycle through the list of files & import to Access creating a new table called Data
DoCmd.TransferText acImportDelim, "Data", "Data", strPath & strFileList(intFile)
fileCounter = Format(intFile, "000") 'format i so that when you use it in file names, the files sort intuitively
Do While Not rs.EOF
sql = "SELECT * FROM Data WHERE Event='" & rs!Event & "'" 'select the records to export and export them
file = "C:\Users\Robbie\Documents\Data Split\" & rs!Event & " " & fileCounter & ".xlsb" 'use the counter to distinguish between which csv your exporting from
qdf.sql = sql
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, qdf.Name, file
sql = "DELETE FROM Data WHERE Event='" & rs!Event & "'" 'delete the records from the source table
DoCmd.RunSQL sql
rs.MoveNext
Loop
rs.MoveFirst
'export remaining data
file = "C:\Users\Robbie\Documents\Data Split\Misc " & fileCounter & ".xlsb" 'use the counter to distinguish between which csv your exporting from
sql = "SELECT * FROM Data"
qdf.sql = sql
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, qdf.Name, file
'delete remaining data
'DoCmd.RunSQL "DELETE FROM Data"
'or delete the table
DoCmd.RunSQL "DROP TABLE Data"
Next
MsgBox UBound(strFileList) & " Files were Imported and Split"
rs.Close
DoCmd.SetWarnings True
End Sub
Create a table with your Events in it (in my example it's called "Events" and has one field "Event").
Create a query called "Export". Doesn't matter what it does, we're going to overwrite it 200 times anyway.
Add the ActiveX Data Objects Library reference
Code:
Dim i As Integer
Dim fileCounter As String
Dim rs As New ADODB.Recordset
Dim sql As String
Dim qdf As QueryDef
Dim file As String
DoCmd.SetWarnings False
Set qdf = CurrentDb.QueryDefs("Export")
sql = "SELECT Event FROM Events"
rs.Open sql, CurrentProject.Connection, adOpenStatic, adLockReadOnly
For i = 1 To x 'where x is however many csvs you're importing
fileCounter = Format(i, "000") 'format i so that when you use it in file names, the files sort intuitively
'run your import code here
Do While Not rs.EOF
'select the records to export and export them
sql = "SELECT * FROM Data WHERE Event='" & rs!Event & "'"
file = "C:\Documents\" & rs!Event & fileCounter & ".xlsb" 'use the counter to distinguish between which csv your exporting from
qdf.sql = sql
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, qdf.Name, file
'delete the records from the source table
sql = "DELETE FROM Data WHERE Event='" & rs!Event & "'"
DoCmd.RunSQL sql
rs.MoveNext
Loop
rs.MoveFirst
'export remaining data
file = "C:\Documents\MISC" & fileCounter & ".xlsb" 'use the counter to distinguish between which csv your exporting from
sql = "SELECT * FROM Data"
qdf.sql = sql
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, qdf.Name, file
'delete remaining data
DoCmd.RunSQL "DELETE FROM Data"
'or delete the table
'DoCmd.RunSQL "DROP TABLE Data"
Next i
rs.Close
DoCmd.SetWarnings True
Make sure none of those files exist before running this, it will not overwrite files. Either delete them manually or you could use the Windows Script Host in the loop to delete the files if they exist before creating them...
Dim fso As New FileSystemObject
If fso.FileExists(file) Then
fso.DeleteFile (file)
End If
In response to your updates:
Consider linking them instead of importing (DoCmd.TransferText acLink, "Data"...). I don't believe it's possible to compact while you're working in a db, it would have to close.
You basically answered your own question. If you want to do that, add the column to the table and update the SQL exactly how you said.
You could use the Replace function but you'd have to run it for each illegal character and you might end up missing one. It's probably best to do what you suggested and just create them yourself in a new column.