how to delete import error tables in access? - ms-access

I am not a VBA expert. what I am trying to do is to import multiple csv files into access. access is creating bunch of import error tables after i import the files. i am using the code below to delete the error tables after i run a macro to import the csv files but it's not working. it's telling me user defined type not defined. any help is appreciated. I really appreciate if you can help me fix that code or find a different one
Sub dropImportError()
Dim tbl_name As DAO.TableDef, str As String
With CurrentDb
For Each tbl_name In .TableDefs
str = tbl_name.Name
If InStr(str, "ImportErrors") <> 0 Then
str = "DROP TABLE" & str & ""
DoCmd.RunSQL str
End If
Next
End With
End Sub

Related

Importing CSV into MS-Access using form button, confusing error

I'm trying to import a CSV file that is created from a web form I developed. When the form submits it creates a record in my CSV with a multitude of customer information.
As per requirements I needed to put it into a CSV, and then separately have it import into an Access database for others to use (Two steps required for server security).
The way I'm trying to do it is with a simple form with a button on it inside Access, that simply says Import, that will pull an update of the CSV whenever the user needs it.
My error is confusing me as it's stating
"Field 'F1' doesn't exist in destination table 'Applications' "
I do not have a field in my CSV labeled F1, or even any record that contains 'F1', and there is no field named F1 in my access table Applications (obviously).
Here is my VB module code from Access
Option Compare Database
Sub ImportingCSV()
Function Import()
On Error GoTo Macro1_Err
DoCmd.TransferText acImportDelim, "", "Applications", "C:\Users\ALee\Documents\formTesting22.csv", False, ""
Import:
Exit Function
Macro1_Err:
MsgBox Error$
Resume Macro1_Exit
End Function
And here is my CSV file format (spaced out for your readability)
OPUCN#WVQNAJT4PD,
2017.05.03,
test,
v,
90545452929,
4062033985,
No,
VM#TEST.VMTEST,
10003937683827,
test,
test,
689 395 3967,
2048 2983999,
No,rle#don.ca,
111 e Streeth south,
12,
Temporary,
Commercial,
100,
200,
300,
208/120V,
Three-Phase,
Underground (UG),
Ganged Position*,
23,
"dsbsdhfbslhfbshfbsdhlfbgshdfgsfslfgljshgfljshgfljshgflsj"
The error is telling me that the field for the second phone number ("4062033985" in the CSV) doesn't have a field in the table Applications, but it does! "F1" in the CSV is Customer Mobile. When I import manually through Access's import wizard this works fine.
Hopefully someone can point me in the right direction, not familiar with VB script or macros in access.
Don't import the file.
Link the csv file as a table. Then create a query to read and convert (purify) the data.
Use this query as source for further processing of the date like appending data to other tables.
a CSV file is a spreadsheet... try...
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml,[YourDestinationTable],"C:\YourFileDirectoryPath, filename, and extension",true,[Spreadsheet name if multiple sheet names]
There are all kinds of ways to do this sort of thing. This is certainly the simplest method.
Private Sub Command0_Click()
DoCmd.TransferText acImportDelim, "", "Book1", "C:\your_path_here\Book1.csv", True, ""
End Sub
Let's say you want to import several CSV files, all of the same type, into the same table. Just run the script below.
Option Compare Database
Option Explicit
Private Sub Command0_Click()
DoImport
End Sub
Function DoImport()
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
' Replace C:\Documents\ with the real path to the folder that
' contains the CSV files
strPath = "C:\your_path_here\"
' Replace tablename with the real name of the table into which
' the data are to be imported
strFile = Dir(strPath & "*.csv")
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()
Loop
End Function
You can do all kinds of other thins too; navigate to a file using the msoFileDialogFilePicker; you can loop through record sets and load them, one by one, into your table. As Gustav suggested, you can link to your file (staging) and write records into a table (production). You should probably try all of these methods, and play around with

Access - custom "was unable to append all data to table"?

I created code for importing data from Excel into desired table, via TransferSheet and builded Query method. I'm also trying to resolve all errors that User could do when Importing data into db (wrong file format, appending 0 rows,field names not same as in DB etc.), but cannot get rid of Error 3059 "was unable to append all data to table" - It occurs when you try to Import some invalid data. I want a custom Msgbox for this error, and stop executing my Query. Here's my code - in short :
Private Sub CmdImport_Click()
Dim SQL As String
Dim dbs As DAO.Database
Set dbs = CurrentDb
On Error GoTo ERR1
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "NEWTABLE", "<Imported file>", True
SQL = " INSERT INTO MyTable (Field1)" & _
" SELECT DISTINCT" & _
" FROM NEWTABLE"
DoCmd.SetWarnings False
dbs.Execute SQL
DoCmd.RunSQL "DELETE * FROM NEWTABLE"
DoCmd.SetWarnings True
ERR1:
If Err.Number = 3059 Then
MsgBox "This file doesn't have proper data to import. Import canceled !"
Exit Sub
End If
End Sub
This code pops-up custom Msgbox after Access allready opens built-in window, regardless of DoCmd.SetWarnings False. If I move DoCmd.SetWarnings False before TransferSheet method, import gets executed and no Msgbox is displayed - which is wrong. How can I handle this error, anybody knows ??
You could import to a temp table.
Then read this with a query that converts and cleans the data, and use this query for your further processing - which now will run without errors caused by malformed data.
I have figured out another way to solve this. I have put all controls that I need before DoCmd.TransferSheet method, including eliminating error that causes "was unable to append all data to table". I added code for checking excel file, and If Excel file data doesn't match criteria, DoCmd.TransferSheet is not performed - so therefore error "was unable to append all data to table" doesn't appear at all. Here It is (part of code which first checks If Excel file data is proper to perform DoCmd.TransferSheet import) :
Dim XcelApp As Object
Dim x, i
Set XcelApp = CreateObject("Excel.Application")
XcelApp.ScreenUpdating = False
XcelApp.Workbooks.Open("C:\Users\Lucky\Desktop\Test\Sample.xlsx")
With XcelApp
i = XcelApp.Rows(1).Find(What:="Število", LookIn:=xlValues, Lookat:=xlWhole).Column
x = XcelApp.Range(XcelApp.Cells(1, i), XcelApp.Cells(XcelApp.Rows.Count, i).End(xlUp)).Value
For i = 2 To UBound(x)
If Not IsNumeric(x(i, 1)) Then
ExcelApp.Quit
Set ExcelApp = Nothing
MsgBox "This Excel file is not valid"
: Exit Sub
End If
Next i
End With
XcelApp.Quit
XcelApp = Nothing
Code is snapshop from this solved thread: loop through Excel columns

Disable Import errors table in Ms Access

Just to start with , I am not a very experienced programmer in Access. Is there any way I can disable the import error tables which are auto generated by access when you import files from excel ?
The reason I want to do this is my excel file has about 4000 rows with data about different locations,now the location I have to do the reporting on is importing properly thats why I am not worried about about the import errors . Also, it only detects the error in one row and because I import the table from vba code it will keep generating this error tables and I end up with big bunch of them.
I did some research but I find answer about solving the issue by fixing the file format of import , but I failed to get the answer about how to disable them.
Appreciate if anyone can help.
EDIT :
After suggestion from #parfait following code did the trick. Any other suggestions are also welcome.
Sub dropImportError()
Dim tbl_name As DAO.TableDef, str As String
With CurrentDb
For Each tbl_name In .TableDefs
str = tbl_name.Name
If InStr(str, "ImportErrors") <> 0 Then
str = "DROP TABLE" & str & ""
DoCmd.RunSQL str
End If
Next
End With
End Sub
Just came across this issue myself, after running the import of procedure I immediately ran the following code which was saved in a stand-alone Module. Simply paste the function DeleteImportErrors into the macro, procedure, or function.
Module code:
Public Function DeleteImportErrors()
Dim n As Integer
Dim db As DAO.Database
Set db = CurrentDb
For n = db.TableDefs.Count - 1 To 0 Step -1
' loop through all tables
If InStr(1, db.TableDefs(n).Name, "ImportError") > 0 Then
' if table is import errors table
DoCmd.DeleteObject acTable, db.TableDefs(n).Name
' delete table
End If
Next n
End Function
'Delete Import Error tables
Private Sub Delete_Error_Tables()
Do Until IsNull(DLookup("Name", "Msysobjects", "Name like '*ImportErrors*'"))
DoCmd.DeleteObject acTable, DLookup("Name", "Msysobjects", "Name like '*ImportErrors*'")
Loop
End Sub

VBA procedure to import csv file into access

i need procedure in VBA to import data into access from csv excel file without some records,, as header and footer. Example,,, i have table in csv file, which contains some
sentence which not belong table date
A1 this is some sentence title.......
A2 title
A3.......
A7 DATA DATA DATA DATA DATA
A8 rows DATA DATA DATA DATA DATA
......
....
A256 DATA DATA DATA DATA
A257 this is some sentence
My Acess shoud contain only rows between A7 to A256. Does anyone knows procedure or whatever in VBA who solves my problems ?
thanks a lot
Edit
The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.
You can link the table either manually or with VBA like this
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
Update
Dim db As DAO.Database
' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next: db.TableDefs.Delete "tblImport": On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh
' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
& "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close: Set db = Nothing
Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work
Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant
sFileIn = "z:\docs\FileName.csv"
sFileOut = "z:\docs\FileOut.csv"
Set fs = CreateObject("Scripting.FileSystemObject")
Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading
sTmp = tsIn.ReadAll
Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
aryFile = Split(sTmp, vbCrLf)
''Start at line 3 and end at last line -1
For i = 3 To UBound(aryFile) - 1
tsOut.WriteLine aryFile(i)
Next
tsOut.Close
DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub
Edit re various comments
It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.
About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003
Introduction to importing and exporting data -- Applies to: Microsoft Access 2010
Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by #Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.

automatically convert access db

I have an access database, with a query made. I need to automate it so that each night this query can run and export to a tab delimited csv file. It is not possible to export a query to a csv file from within access. My question is, are there any tools that can select certain tables, or perform an sql query on an mdb file, and export to a csv file?
Actually, you can export a query to a csv file from within Access.
You can do this with a Macro using the TransferText method.
Macro:
Name = ExportQuery
Action = TransferText
Transfer Type = Export Delimited
Table Name = [name of your Access query]
File Name = [path of output file]
Has Field Names = [Yes or No, as desired]
You can execute the macro from the command line like this:
"[your MS Office path]\msaccess.exe" [your databse].mdb /excl /X ExportQuery /runtime
Since you're having trouble with TransferText in a macro try this:
1) Create a Module named "ExportQuery". In this module, create a function called "ExportQuery":
Function ExportQuery()
DoCmd.TransferText acExportDelim, , "[your query]", "[output file].csv"
End Function
2) Create a Macro named RunExportQuery:
Action = RunCode
Function Name = ExportQuery ()
VBScript works quite well with the Jet engine. However, I do not see why you say " It is not possible to export a query to a csv file from within access."
Sub TransferCSV()
DoCmd.TransferText acExportDelim, , "PutNameOfQueryHere", "C:\PutPathAnd\FilenameHere.csv", True
End Sub
Is the usual way in VBA.
EDIT:
It is possible to run a VBScript file (.vbs) from the command line. Here is some sample VBScript to output a tab delimited file.
db = "C:\Docs\LTD.mdb"
TextExportFile = "C:\Docs\Exp.txt"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source =" & db
strSQL = "SELECT * FROM tblMembers"
rs.Open strSQL, cn, 3, 3
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.CreateTextFile(TextExportFile, True)
a = rs.GetString
f.WriteLine a
f.Close
SQL Server Integration Services is able to do the transformation that you are talking about. Don't be fooled by the name, because you don't need SQL Server in order to automate and run the packages.
http://msdn.microsoft.com/en-us/library/ms141026.aspx