I got an .mdb with 200 tables.
I want to write a vba routine that exports data into separate CSV.
On google I've found this code:
Public Sub ExportAllTablesToCSV()
Dim i As Integer
Dim name As String
For i = 0 To CurrentDb.TableDefs.Count
name = CurrentDb.TableDefs(i).name
If Not Left(name, 4) = "msys" And Not Left(name, 1) = "~" Then
DoCmd.TransferText acExportDelim, "", name, _
"c:\exports\" & name & ".csv", _
True
End If
Next i
End Sub
It seems ok but it wants a Export Specification (the parameter after acExportDelim"), this makes the script useless as I don't want to manually create 200 Export Specification.
Any idea?
This worked for me.
Option Compare Database
Option Explicit
Private Sub Command0_Click()
On Error GoTo Err_ExportDatabaseObjects
Dim db As Database
Dim td As TableDef
Dim d As Document
Dim c As Container
Dim i As Integer
Dim sExportLocation As String
Set db = CurrentDb()
sExportLocation = "C:\all_files\"
For Each td In db.TableDefs 'Tables
If Left(td.Name, 4) <> "MSys" Then
DoCmd.TransferText acExportDelim, , td.Name, sExportLocation & "Table_" & td.Name & ".csv", True
End If
Next td
Set db = Nothing
Set c = Nothing
MsgBox "All database objects have been exported as a csv file to " & sExportLocation, vbInformation
Exit_ExportDatabaseObjects:
Exit Sub
Err_ExportDatabaseObjects:
MsgBox Err.Number & " - " & Err.Description
Resume Exit_ExportDatabaseObjects
End Sub
Are you shure you want CSV option? As this format with you can't import tables back to ms access (cause no data schema saved) so you need 200 files with schema. Ok if csv - there is a page https://learn.microsoft.com/en-us/office/vba/api/access.docmd.transfertext. Me, I tryed other more convinient way with XML In case you want to save your tables in convertible format
Dim db As DAO.Database
Dim td As DAO.TableDefs
Set db = CurrentDb()
Set td = db.TableDefs
For Each t In td 'loop through all the fields of the tables
'Ignore any system tables
If Left(t.Name, 4) = "MSys" Then GoTo Continue
DoCmd.OutputTo acOutputTable, t.Name, , _
(strPathAndFileName & t.Name & ".xml"), False
Continue:
Next
`
You will be prompted for any t selected with format confirm
format and schema
So you have to click 3 x 200 times with keys or mouse, then in ~ten minutes work will be done.
Related
I am creating an automated process that exports 50 tables I have in access to a CSV. The issue I'm having is one row in a table has carriage returns or line breaks mixed in. When I open the exported CSVs as a text file, some lines are broken up.
The data type for the troublesome row are all text. I need help integrating a statement in my VBA script to remove the spaces in front of any characters & remove any line breaks or carriage returns as well.
There is only one column in this one table giving me issues.
I have tried Trim & Replace statements that don't seem to work. It could be caused from not writing them correctly.
Option Compare Database
Option Explicit
Public Sub ExportDatabaseObjects()
On Error GoTo Err_ExportDatabaseObjects
Dim db As Database
Dim td As TableDef
Dim d As Document
Dim c As Container
Dim i As Integer
Dim sExportLocation As String
Set db = CurrentDb()
sExportLocation = "C:\File Path\"
For Each td In db.TableDefs 'Tables
If Left(td.Name, 4) <> "MSys" Then
CurrentDB.execute " UPDATE " & td.Name & " SET yourColumn='" & REPLACE(yourColumn, CHAR(13)+CHAR(10), "") & "' WHERE INSTR(1, yourColumn, CHAR(13)+CHAR(10))>0"
DoCmd.TransferText acExportDelim, , td.Name, sExportLocation & "Table_" & td.Name & ".csv", True
End If
Next td
Set db = Nothing
Set c = Nothing
MsgBox "All database objects have been exported as a csv file to " & sExportLocation, vbInformation
Exit_ExportDatabaseObjects:
Exit Sub
Err_ExportDatabaseObjects:
MsgBox Err.Number & " - " & Err.Description
Resume Exit_ExportDatabaseObjects
End Sub
My VBA script successfully exports all tables in my access database into the folder I want. Now I need some help cleaning up the data before it goes into production.
For Each td In db.TableDefs 'Tables
If Left(td.Name, 4) <> "MSys" Then
CurrentDB.execute " UPDATE " & td.Name & " SET yourColumn='" & REPLACE(yourColumn, CHAR(13)+CHAR(10), "") & "' WHERE INSTR(1, yourColumn, CHAR(13)+CHAR(10))>0"
DoCmd.TransferText acExportDelim, , td.Name, sExportLocation & "Table_" & td.Name & ".csv", True
End If
Next td
This should help you find and replace bad characters
I have an Access 2013 database with all tables linked to SQL Server 2016 tables. I have an Excel 2013 (.xlsx) file, that I need to import into a a table in Ms Access that is linked to SQL Server via vba Code (all fields in xlsx and table are the same)
All my VBA code resides in the Access database, I have a form with a button with event in it, I try to use de "transferspreadsheet", an "Insert to" Clause for sql but neither of them has worked for me
Here is my code,
xtRuta2 name of the field in the form that have the path
Dim strArchivo2 String ' path of the file xlsx c:\reports\mireporte.xlsx
dim miAlerta2 as string
Dim ssql As String
strArchivo2 = txtRuta2
miAlerta2 = MsgBox("¿Do you want to import new information for " & strArchivo2 & "?" & vbCrLf & vbCrLf & "This operation will be update all the information", vbExclamation + vbOKCancel, "¡INFORMATION IMPORT ALERT!")
If miAlerta2 = vbOK Then
varAlert2 = MsgBox("Please confirm you want to import new information?", vbExclamation + vbOKCancel, "¡CONFIRMATION IMPORT ALERT!")
If varAlert2 = vbOK Then
'DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "tbl_ZSales_Export Worksheet", strArchivo2, True, "Export Worksheet$"
ssql = "INSERT INTO [tbl_Export Worksheet] select * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=" & strArchivo2 & ";HDR=YES', 'SELECT * FROM [Export Worksheet$)'"
'CurrentDb.Execute ssql
MsgBox "Import Finished", vbExclamation + vbOKOnly
endif
end if
Can you please help me to write the correct code for this to work
Thanks regards!
This piece of code (late bdingin interaction with excel) is used to convert excel sheet to text file and then import to a table of your choosing. I prefer to use this method as access has an annoying habit of trying ot interpret your data for you when using transferspreadsheet. With creating an import spec (which you need to do to use this method), you can easily predefine the data types.
Option Compare Database
Option Explicit
Private Sub stuff()
On Error GoTo GetAccrualFile_Err
Dim fileLoc As String
Dim path As String, Sep As String, NewTextFile As String, WholeLine As String
Dim oXL As Object, sheet As Object
Dim i As Long, j As Long, counteri As Long, counterj As Long
Dim bringOver As Variant
DoCmd.SetWarnings False
DoCmd.Hourglass True
counteri = 0
counterj = 0
Sep ="your prefered delimiter"
DoCmd.RunSQL "DELETE * FROM TBL"
fileLoc = "UNC PATH AND FILE NAME" & ".xlsx"
path = Left(fileLoc, InStrRev(fileLoc, "\") - 1) & "\"
NewTextFile = "UNC PATH AND FILE NAME" & ".txt"
Set oXL = CreateObject("Excel.Application")
With oXL
.WorkBooks.Open FileName:=path & Dir$(fileLoc)
Open NewTextFile For Output As #2
bringOver = .Worksheets("your sheet name").UsedRange 'you might need to adjust this line to get the sheet your after
For i = LBound(bringOver, 1) To UBound(bringOver, 1)
For j = LBound(bringOver, 2) To UBound(bringOver, 2)
WholeLine = WholeLine & bringOver(i, j) & Sep
counterj = counterj + 1
Next j
'used if you want to skip column headers
If counteri <> 0 Then
Print #2, WholeLine
End If
WholeLine = ""
counteri = counteri + 1
counterj = 0
Next i
counteri = 0
Erase bringOver
End With
Close #2
DoCmd.TransferText acImportDelim, "importspecname", "tbltoimportto", NewTextFile, False
'***************************************************************************************
'you will need to learn how to set up import specs, as well as understand the arguments for DoCmd.TransferText
'***************************************************************************************
CleanUp:
DoCmd.SetWarnings True
DoCmd.Hourglass False
On Error Resume Next
DoEvents
oXL.Quit
oXL.Application.Quit
If Dir(NewTextFile) <> "" Then Kill NewTextFile
Erase bringOver
DoCmd.SetWarnings True
DoCmd.Hourglass False
Exit Sub
GetAccrualFile_Err:
DoCmd.SetWarnings True
DoCmd.Hourglass False
msgbox "An error has occured. " & " " & ERR.Number & " " & ERR.Description & " "
GoTo CleanUp
Resume
End Sub
Try EPPlus, a free library which allows you to manage Excel files from .Net platform.
Here you have a tutorial: https://riptutorial.com/epplus
im working with access and VBA. As for now, I am trying to create a query with a SQL statement.
I have a bunch of tables, all of them are named "innen" at the end and they vary at the start. Each of these tables contain the column name "OP" (also other field names). Now my goal is to select all tables with the name containing '%innen' and the column name "OP". So far i tried this:
Sub Aktuell()
Dim strSQL As String
Dim db As DAO.Database
Set db = CurrentDb
Dim qdf As QueryDef
strSQL = "SELECT [*].OP FROM MSysObjects WHERE TABLE_NAME LIKE '%innen' ORDER BY MAX;"
db.Execute strSQL
Set qdf = CurrentDb.CreateQueryDef("NewQuery8", strSQL)
DoCmd.OpenQuery qdf.Name
End Sub
i tried this here aswell:
strSQL = "SELECT * " & _
"FROM INFORMATION_SCHEMA.TABLES " & _
"WHERE COLUMN_NAME = 'OP_Datum';"
But i keep getting errors.
Any ideas? does it even work with a sql statement via vba?
Here is a VBA solution for you.
Option Compare Database
Function GetFieldList(TableName As String) As String()
On Error GoTo Er
Dim Flds() As String
Dim fc As Long
Dim I As Long
'Initialize Dynamic Flds() Array
Flds = Split("")
fc = CurrentDb.TableDefs(TableName).Fields.Count - 1
If fc >= 0 Then
ReDim Preserve Flds(fc)
For I = 0 To fc
Flds(I) = CurrentDb.TableDefs(TableName).Fields(I).Name
Next I
End If
Done:
GetFieldList = Flds
Erase Flds
Exit Function
Er:
Resume Done
End Function
Sub flTest()
Dim I As Long
Dim Fields As Variant
Fields = GetFieldList("Customers")
If UBound(Fields) = -1 Then
MsgBox "Table Not Found, or Table has no fields", vbCritical + vbOKOnly
Exit Sub
End If
For I = LBound(Fields) To UBound(Fields)
Debug.Print """" & Fields(I) & """"
Next I
End Sub
I'll bet there is a way to so the same thing using nothing but SQL. Although, Access is a unique animal. You can do this using SQL Server. I'm not 100% sure Access can handle it. Well, why not try it and see for yourself.
I'm trying to add several new columns to a table that already exists in Access 2007 or 2010 with a query. Right now my code looks like this (yes, I'm terribly new to this):
ALTER TABLE AC_PROPERTY
ADD JAB_1 double,
JAB_2 double,
JAB_3 double;
This correctly adds the three columns when none of them already exist, but if any of them exist I get an error message and the query fails to run. I need it to add each columns only if it does not exist. Can anyone please help with what my code should look like to check if each column exists before trying to add it?
NOTE: I would just do 3 queries for each column, but I actually need to add 20+ columns. This is just a simple example of my actual use.
Thanks a billion!
Here is some old code.... it would be better to just check all fields in the same subroutine rather than opening/closing the DB, TDF, etc.
Option Compare Database
Option Explicit
Function Check_If_Exists()
Dim strStatus As String
' Add calls for the fields you want to append
strStatus = Add_Field("MyFLd2", "Double")
If strStatus = "Exists" Then
Debug.Print "field present"
ElseIf strStatus = "Added" Then
Debug.Print "field added"
End If
End Function
Function Add_Field(strFN, strType) As String
Dim db As DAO.Database
Dim td As DAO.TableDef
Dim fd As DAO.Field
Dim strSQL As String
On Error GoTo Error_Trap
Set db = CurrentDb
Set td = db.TableDefs("Table1")
' ' List all field names
' For Each fd In td.Fields
' Debug.Print fd.Name
' Next fd
If IsNull(td.Fields(strFN)) Then
Add_Field = "Exists"
End If
Set fd = Nothing
Set td = Nothing
Set db = Nothing
Exit Function
Error_Trap:
Debug.Print Err.Number & vbTab & Err.Description
If Err.Number = 3265 Then
Add_Field = "Added"
strSQL = "alter table Table1 ADD " & strFN & " " & strType & ";"
db.Execute strSQL
db.TableDefs.Refresh
End If
Exit Function
Resume
End Function
I have an access database which manipulates data from a Magento e-commerce store, reformats the data and (hopefully!) spits out a CSV file which can then be imported into ebay Turbolister for mass upload to eBay.
I have got as far as creating a query which correctly lays out the data into the format required by Turbolister.
My issues are various (including some which appear to be related to Access' handling of large field contents), however the crux of my problem is that I am struggling to get working a simple script which exports the query results as a properly formatted CSV (including doubling up on double quotes where required inside a text value i.e. if the value itself contains quotes which need to be retained).
The DoCmd.TransferText solution throws an error related to field size ('the field is too small to accept the amount of data you attempted to add') so thats no good.
Has anyone got a good working CSV export routine in VBA that they can suggest?
Cheers
This is an old function I sometimes used to use, it allows you to specify the delimeter, it also checks the data it's outputting and if it can't be evaluated to either a date or a numeric etc, then it uses double quotes:
Public Function ExportTextDelimited(strQueryName As String, strDelimiter As String)
Dim rs As Recordset
Dim strHead As String
Dim strData As String
Dim inti As Integer
Dim intFile As Integer
Dim fso As New FileSystemObject
On Error GoTo Handle_Err
fso.CreateTextFile ("C:\Untitled.csv")
Set rs = Currentdb.OpenRecordset(strQueryName)
rs.MoveFirst
intFile = FreeFile
strHead = ""
'Add the Headers
For inti = 0 To rs.Fields.Count - 1
If strHead = "" Then
strHead = rs.Fields(inti).Name
Else
strHead = strHead & strDelimiter & rs.Fields(inti).Name
End If
Next
Open "C:\Untitled.csv" For Output As #intFile
Print #intFile, strHead
strHead = ""
'Add the Data
While Not rs.EOF
For inti = 0 To rs.Fields.Count - 1
If strData = "" Then
strData = IIf(IsNumeric(rs.Fields(inti).value), rs.Fields(inti).value, IIf(IsDate(rs.Fields(inti).value), rs.Fields(inti).value, """" & rs.Fields(inti).value & """"))
Else
strData = strData & strDelimiter & IIf(IsNumeric(rs.Fields(inti).value), rs.Fields(inti).value, IIf(IsDate(rs.Fields(inti).value), rs.Fields(inti).value, """" & rs.Fields(inti).value & """"))
End If
Next
Print #intFile, strData
strData = ""
rs.MoveNext
Wend
Close #intFile
rs.Close
Set rs = Nothing
'Open the file for viewing
Application.FollowHyperlink "C:\Untitled.csv"
Exit Function
Handle_Err:
MsgBox Err & " - " & Err.Description
End Function
It may need a couple of tweaks as I've taken out some bits which were only relevant to my particular case but this may be a starting point.