Import append vba MS-Access - ms-access

Need help with the Access VBA
I am trying to import spreadsheets from excel into access. Once it is imported it will be appended into a different table and the import table will be deleted so that i can then import a new spreadsheet. However i have error when appending i need to append the entire table because i will not always know the header from the spreadsheet and how many their are.
Please Help. Below is the code i have been work on.
Module-
Option Compare Database
Function selectFile()
Dim fd As FileDialog, fileName As String
On Error GoTo ErrorHandler
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
If fd.Show = True Then
If fd.SelectedItems(1) <> vbNullString Then
fileName = fd.SelectedItems(1)
End If
Else
'Exit code if no file is selected
End
End If
'Return Selected FileName
selectFile = fileName
Set fd = Nothing
Exit Function
ErrorHandler:
Set fd = Nothing
MsgBox "Error " & Err & ": " & Error(Err)
End Function
VBA -
Private Sub cmdImportNoDelete_Click()
'Unset warnings
DoCmd.SetWarnings False
'Import spreadsheet
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "Import", selectFile, True
'SQL append statement, Needs to append entire table (must be able to append multiply table with different headers
DoCmd.RunSQL "INSERT INTO Tbl_ImportDump * FROM Import"
'SQL delete Table
DoCmd.DeleteObject acTable, "Import"
DoCmd.SetWarnings True
End Sub

Tbl_ImportDump must exist. If it doesn't already, create it:
DoCmd.RunSQL _
"CREATE TABLE Tbl_ImportDump (Col1 Col1DataType, Col2 Col2DataType, etc)"
Then after importing your spreadsheet (as table Import, as you've already done), get the column names in the Import table, and put these into the insert statement:
dim ImportCols as String: ImportCols = ""
dim ii as long
dim rs as Recordset
rs.OpenRecordset "SELECT TOP 1 * FROM Import"
for ii = 0 to 2
ImportCols = ImportCols & "," & rs.Fields(0).Name
next
importCols = mid(importCols, 2)
DoCmd.RunSQL _
"INSERT INTO Tbl_ImportDump (Col1, Col2, Col3) " & _
"SELECT " & importCols & " FROM Import"

Related

Export Sql query to several excel files

I have 2 tables:
company (rut, name, category, city)
categories (category).
I need to export an excel file for each category with the corresponding companies.
I have the query:
Select * from company c
inner join categories cy on c.category = cy.category;
That is not what I need But each group of combinations is exported to a different excel file.
Thank you.
If you want to export it one by one use this code:
SELECT * FROM COMPANY WHERE CATEGORY = (NAME OF CATEGORY);
If you want to export all:
SELECT * FROM COMPANY ORDER BY CATEGORY ASC;
I dont think you need to join it to "categories" table since you already use the same value from table company.
You can now export your result set.
There are a couple things you can do here.
You can do a big dump to Excel, and copy all unique values in a specific column to a new workbook.
Sub Copy_To_Workbooks()
'Note: This macro use the function LastRow
Dim My_Range As Range
Dim FieldNum As Long
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim CalcMode As Long
Dim ViewMode As Long
Dim ws2 As Worksheet
Dim MyPath As String
Dim foldername As String
Dim Lrow As Long
Dim cell As Range
Dim CCount As Long
Dim WSNew As Worksheet
Dim ErrNum As Long
'Set filter range on ActiveSheet: A1 is the top left cell of your filter range
'and the header of the first column, D is the last column in the filter range.
'You can also add the sheet name to the code like this :
'Worksheets("Sheet1").Range("A1:D" & LastRow(Worksheets("Sheet1")))
'No need that the sheet is active then when you run the macro when you use this.
Set My_Range = Range("A1:D" & LastRow(ActiveSheet))
My_Range.Parent.Select
If ActiveWorkbook.ProtectStructure = True Or _
My_Range.Parent.ProtectContents = True Then
MsgBox "Sorry, not working when the workbook or worksheet is protected", _
vbOKOnly, "Copy to new workbook"
Exit Sub
End If
'This example filters on the first column in the range(change the field if needed)
'In this case the range starts in A so Field:=1 is column A, 2 = column B, ......
FieldNum = 1
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
'Set the file extension/format
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2013
If ActiveWorkbook.FileFormat = 56 Then
FileExtStr = ".xls": FileFormatNum = 56
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
End If
'Change ScreenUpdating, Calculation, EnableEvents, ....
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
ViewMode = ActiveWindow.View
ActiveWindow.View = xlNormalView
ActiveSheet.DisplayPageBreaks = False
'Delete the sheet RDBLogSheet if it exists
On Error Resume Next
Application.DisplayAlerts = False
Sheets("RDBLogSheet").Delete
Application.DisplayAlerts = True
On Error GoTo 0
' Add worksheet to copy/Paste the unique list
Set ws2 = Worksheets.Add(After:=Sheets(Sheets.Count))
ws2.Name = "RDBLogSheet"
'Fill in the path\folder where you want the new folder with the files
'you can use also this "C:\Users\Ron\test"
MyPath = Application.DefaultFilePath
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'Create folder for the new files
foldername = MyPath & Format(Now, "yyyy-mm-dd hh-mm-ss") & "\"
MkDir foldername
With ws2
'first we copy the Unique data from the filter field to ws2
My_Range.Columns(FieldNum).AdvancedFilter _
Action:=xlFilterCopy, _
CopyToRange:=.Range("A3"), Unique:=True
'loop through the unique list in ws2 and filter/copy to a new sheet
Lrow = .Cells(Rows.Count, "A").End(xlUp).Row
For Each cell In .Range("A4:A" & Lrow)
'Filter the range
My_Range.AutoFilter Field:=FieldNum, Criteria1:="=" & _
Replace(Replace(Replace(cell.Value, "~", "~~"), "*", "~*"), "?", "~?")
'Check if there are no more then 8192 areas(limit of areas)
CCount = 0
On Error Resume Next
CCount = My_Range.Columns(1).SpecialCells(xlCellTypeVisible) _
.Areas(1).Cells.Count
On Error GoTo 0
If CCount = 0 Then
MsgBox "There are more than 8192 areas for the value : " & cell.Value _
& vbNewLine & "It is not possible to copy the visible data." _
& vbNewLine & "Tip: Sort your data before you use this macro.", _
vbOKOnly, "Split in worksheets"
Else
'Add new workbook with one sheet
Set WSNew = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
'Copy/paste the visible data to the new workbook
My_Range.SpecialCells(xlCellTypeVisible).Copy
With WSNew.Range("A1")
' Paste:=8 will copy the columnwidth in Excel 2000 and higher
' Remove this line if you use Excel 97
.PasteSpecial Paste:=8
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
.Select
End With
'Save the file in the new folder and close it
On Error Resume Next
WSNew.Parent.SaveAs foldername & _
cell.Value & FileExtStr, FileFormatNum
If Err.Number > 0 Then
Err.Clear
ErrNum = ErrNum + 1
WSNew.Parent.SaveAs foldername & _
"Error_" & Format(ErrNum, "0000") & FileExtStr, FileFormatNum
.Cells(cell.Row, "B").Formula = "=Hyperlink(""" & foldername & _
"Error_" & Format(ErrNum, "0000") & FileExtStr & """)"
.Cells(cell.Row, "A").Interior.Color = vbRed
Else
.Cells(cell.Row, "B").Formula = _
"=Hyperlink(""" & foldername & cell.Value & FileExtStr & """)"
End If
WSNew.Parent.Close False
On Error GoTo 0
End If
'Show all the data in the range
My_Range.AutoFilter Field:=FieldNum
Next cell
.Cells(1, "A").Value = "Red cell: can't use the Unique name as file name"
.Cells(1, "B").Value = "Created Files (Click on the link to open a file)"
.Cells(3, "A").Value = "Unique Values"
.Cells(3, "B").Value = "Full Path and File name"
.Cells(3, "A").Font.Bold = True
.Cells(3, "B").Font.Bold = True
.Columns("A:B").AutoFit
End With
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
If ErrNum > 0 Then
MsgBox "Rename every WorkSheet name that start with ""Error_"" manually" _
& vbNewLine & "There are characters in the name that are not allowed" _
& vbNewLine & "in a sheet name or the worksheet already exist."
End If
'Restore ScreenUpdating, Calculation, EnableEvents, ....
My_Range.Parent.Select
ActiveWindow.View = ViewMode
ws2.Select
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlValues, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
https://www.rondebruin.nl/win/s3/win006_3.htm
Also, you can split a table/query into several separate Excel files using SSIS. I'm not sure you can do this kind of thing using pure SQL.
I suppose you could use Excel to create queries with where clauses, and filter for all unique records in a table, export each unique batch to worksheet, and then save each worksheet as a separate file. I can imagine that it would run pretty slow on a large table.

MS Access Linked Table Manager doesn't update new data source

I have an MS Access 2010 Database that has a table that is linked to a CSV file. Upating the CSV files location using the inbuilt Access "Linked Table Manager" doesn't work.
I check the file i want to update, choose "always prompt for new location" and select the new file. I get a message telling me that the update was successful, but when I go to check, the table is still linked to the old file.
Is this a MS Access bug and if so what is the most efficient workaround?
I ended up deleting the old table and manually recreating a new table with the same specifications.
*Updated: -- I forgot to include the referenced Function Relink_CSV :(
Yes, I would call it a bug. Microsoft probably calls it a 'design characteristic'.
As you have discovered, you can manually fix the issue. If you are interested in a code solution, then I may have something that will work for you -- if your CSV file is delimited by comma's.
The following code (which you need to modify!) will delete the existing linked csv file, then add a link to the same file. For debugging, my code then deletes that link and adds a link to a different file name, but in the same folder.
There are other solutions that make use of a saved Import Specification, that you can reuse, if your csv format is not simple.
Option Explicit
Option Compare Database
Sub Call_Relink()
Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim strTableName As String
Dim strPath As String
Dim strFile As String
Dim iReply As Integer
iReply = MsgBox("WARNING!!!! This code will remove the linked tables 'FileA' and 'FileB'" & vbCrLf & vbCrLf & _
"Click 'Yes' to Continue" & vbCrLf & "Click 'No' to Stop", vbYesNo, "CAUTION!! Will remove linked table(s)")
If iReply <> vbYes Then
Exit Sub
End If
On Error GoTo Error_Trap
Set dbs = CurrentDb
dbs.TableDefs.Delete "FileA" ' For testing; delete table if it already exists
strPath = "C:\Temp\"
strFile = "FileA.csv"
strTableName = "FileA" ' Table name in Access
Relink_CSV strTableName, strPath, strFile ' Call function to link the CSV file
dbs.TableDefs.Refresh ' Refresh TDF's
Debug.Print "Pause here and check file link" ' Put a breakpoint here; pause and look at the table in Access
dbs.TableDefs.Delete "FileA" ' For testing; delete table if it already exists
strPath = "C:\Temp\" ' Path to next csv
strFile = "FileB.csv" ' Name of next csv file
strTableName = "FileA" ' Table name in Access
Relink_CSV strTableName, strPath, strFile ' Call function to link to a different CSV file
dbs.TableDefs.Refresh
Debug.Print "Pause here and check file link" ' Put a breakpoint here; pause and look at the table in Access
My_Exit:
Set dbs = Nothing
Exit Sub
Error_Trap:
Debug.Print Err.Number & vbTab & Err.Description
If Err.Number = 3265 Then ' Item not found in this collection.
' Ignore this error
Resume Next
End If
MsgBox Err.Number & vbTab & Err.Description
Resume My_Exit
Resume
End Sub
Function Relink_CSV(strTableName As String, strPath As String, strFile As String)
' (1) Name of the table in Access
' (2) Path to the file
' (3) File name
On Error GoTo Relink_Err
DoCmd.TransferText acLinkDelim, , strTableName, strPath & strFile, False, ""
Relink_Exit:
Exit Function
Relink_Err:
Debug.Print Err.Number & vbTab & Err.Description
MsgBox Err.Number & vbTab & Err.Description
Resume Relink_Exit
Resume
End Function

Searching for a value in Access Table VBA

I have written code that imports excel files into a access table. As each file is imported the file name is recorded and saved to a separate table named 'FilesDownloaded'.
I would like to add vba code that prior to importing the file it will check to see if the name of the file (myfile) is already saved on the 'FilesDownloaded' table. This will prevent the same file from being imported twice.
Code:
Function Impo_allExcel()
Dim myfile
Dim mypath
Dim que As Byte
Dim rs As DAO.Recordset
que = MsgBox("This proces will import all excel items with the .xls in the folder C:\MasterCard. Please make sure that only the files you want imported are located in this folder. Do you wish to proceed?", vbYesNo + vbQuestion)
If que = 7 Then
Exit Function
Else
'do nothing and proceed with code
End If
DoCmd.SetWarnings (False)
DoCmd.RunSQL "DELETE * FROM tblMaster_Import;"
MsgBox "Please WAIT while we process this request"
mypath = "C:\Master\"
ChDir (mypath)
myfile = Dir(mypath & "*.xls")
Do While myfile <> ""
If myfile Like "*.xls" Then
'this will import ALL the excel files
'(one at a time, but automatically) in this folder.
' Make sure that's what you want.
'DoCmd.TransferSpreadsheet acImport, 8, "tblMasterCard_Import", mypath & myfile
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel8, "tblMaster_Import", mypath & myfile, 1
Set rs = CurrentDb.OpenRecordset("FilesDownloaded")
rs.AddNew
rs.Fields("Filename").Value = myfile
rs.Update
rs.Close
Set rs = Nothing
End If
myfile = Dir()
Loop
'append data to tblAll (risk of duplicates at this point)
DoCmd.RunSQL "INSERT INTO tblAll SELECT tblMaster_Import.* FROM tblMaster_Import;"
DoCmd.OpenQuery "qryUpdateDateField", acViewNormal
''this code will apend to an existing table and runs the risk of doubling data.
DoCmd.SetWarnings (True)
MsgBox "Your upload is complete"
End Function
A possible solution is to make a query, which gives you the result of lines in the table FilesDownloaded, with condition that the name is equal to your file. Something like this:
countString = "SELECT COUNT(*) FROM [FilesDownloaded] WHERE [NAMEOFCOL] = " & myFile
Then run the query, and if the result is more than 1, you obviously have it.

Adding DBfailonerror in access vb creates compile error invalid use of property

An import sub that has been created in access works OK but when DBfailonerror is added a compile error invalid use of property is encountered when the sub is run from the vb editor.
Any advice re: this would be most appreciated. Code is as follows:
Sub Importcl()
'DATA DECLARATIONS
Dim fso As New FileSystemObject
Dim t As TextStream
Dim strFilePath As String
Dim Cnr As String
Dim Cnri As String
Dim Cnrii As String
Dim Cnriii As String
Dim Sqlstr As String
Dim Db As DAO.Database
'SET COUNTERS TO ZERO
Cnr = 0
Cnri = 0
Cnrii = 0
Cnriii = 0
'Point to DB
Set Db = CurrentDb()
'SET TXT FILE PATH
strFilePath = "C:\Users\Vlad\CSV import\EV WORK\Book1.txt"
'ERROR HANLDER FOR TXT FILE PATH AND COUNTING OF TXT FILE LINE ITEMS
If fso.FileExists(strFilePath) Then
Set t = fso.OpenTextFile(strFilePath, ForReading, False)
Do While t.AtEndOfStream <> True
t.SkipLine
Cnr = Cnr + 1
Loop
t.Close
Else: MsgBox ("Txt File not Found - Check File Path")
Exit Sub
End If
'DISPLAY LINE RECORDS COUNTED IN TXT FILE TO BE ADDED TO TABLE
Debug.Print Cntr; " Incl header"
MsgBox (Cnr - 1 & " records to be added")
'COUNT & DISPLAY CURRENT RECORD COUNT IN TARGET TABLE
Cnri = DCount("[Case Date]", "All Caseload Data New")
If MsgBox(Cnri & " -Current Records in table- All Caseload Data New - Continue
with Import?", vbYesNo, "Import") = vbYes Then
Db.Execute _
"INSERT INTO [All Caseload Data New] SELECT * FROM[Text;FMT=Delimited;HDR=Yes;
DATABASE=C:\Users\Dev\CSV import\DEV WORK\].[Book1#txt];"
dbFailOnError
Db.TableDefs.Refresh
Else: Exit Sub
End If
Cnrii = DCount("[Case Date]", "All Caseload Data New")
Cnriii = Cnrii - Cnri
MsgBox (Cnriii & " New records added to table All Caseload Data New")
End Sub
With this code to start ...
Dim db As DAO.database
Dim strInsert As String
strInsert = "INSERT INTO tblFoo (some_text) VALUES ('bar');"
Set db = CurrentDb
Then these 2 Execute statements ..
db.Execute strInsert
dbFailOnError ' triggers error
db.Execute strInsert, dbFailOnError ' compiles without error
Include dbFailOnError on the same line as Execute. Placing dbFailOnError on a separate line triggers that "invalid use of property" compile error.

Import csv, export queries, delete queries then repeat

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.