I have a report that exports to a CSV. It works fine, but what if I want only the first column to actually export in the file instead of everything? Here's what I have:
Private Sub EthosRpt_Click()
DoCmd.SetWarnings (WarningsOff)
Dim FileName As String
DoCmd.OpenQuery "QryEthosCSV"
FileName = Environ("UserProfile") & "\Desktop\EthosRpt.csv"
DoCmd.TransferText acExportDelim, , "EthosData", FileName, False
DoCmd.SetWarnings (WarningsOn)
End Sub
Build a new query that contains exactly the column(s) you want to export, then use this query with DoCmd.TransferText.
Related
I am working on an export code to copy and export the current record I am viewing to an excel spreadsheet. Below is my code
Private Sub cmdExportFilename_Click()
Dim sFilename As String
Dim StrSQL As String
StrSQL = "Select * FROM [MainData] WHERE ([ID]=" & Me![ID] & ");"
sFilename = "C:\Desktop\exportResults.xlsx"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, StrSQL,
sFilename, True
End Sub
When I run this I get a Run-time error '3011' saying it could not find the object (though it pulls my Select string and correctly identifies I'm viewing record 86 with the error message" and says the object doesn't exist.
My previous code successfully exported data but it outputted the entire query results instead of just the viewed record.
Private Sub cmdExportFilename_Click()
Dim sFilename As String
sFilename = "C:\Users\cpastore\Desktop\exportResults.xlsx"
DoCmd.OutputTo acOutputForm, "OpenComplaintsQuery", acFormatXLSX, sFilename,
AutoStart:=True
End Sub
With Outputto command I do not see where I can select certain things in Parameters. So I thought I would try TransferSpreadsheet command instead.
My end goal ultimately is with the record I am viewing, when I click the button, it exports 6 or 7 fields of 25 that the form displays to an excel spreadsheet where those values Goto a very specific cell location in the sheet. I know with codes above I am a long way from there but I am slowly learning.
Edit: Adding new Code per June7 post suggestion. Ran into another Runtime Error
Private Sub cmdExportfield_Click()
Dim rsGroup As DAO.Recordset
Dim QIMS As String
Dim path As String
path = "C:\Desktop\"
Set rsGroup = CurrentDb.OpenRecordset("SELECT
OpenComplaintsQuery.QIMS# " & "FROM OpenComplaintsQuery GROUP
BY OpenComplaintsQuery.QIMS#", dbOpenDynaset)
Do While Not rsGroup.EOF
QIMS = rsGroup!QIMS#
Dim rsExportSQL As String
rsExportSQL = "Select * FROM OpenComplaintsQuery" & "WHERE
(((OpenComplaintsQuery.QIMS#='" & QIMS & "'))"
Dim rsExport As DAO.QueryDef
Set rsExport = CurrentDb.CreateQueryDef("myexportquerydef",
rsExportSQL)
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9,
"myexportquerydef", path & "exporttest.xlsx", True
CurrentDb.QueryDefs.Delete rsExport.Name
rsGroup.MoveNext
Loop
End Sub
When I run this, I get run time error 3027: "Cannot update. Database or object is read-only."
Private Sub Export_Run()
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogSaveAs)
If fd.Show = True Then
If Format(fd.SelectedItems(1)) <> vbNullString Then
DoCmd.TransferText acExportDelim, , "Export_tbl", fd.SelectedItems(1), False
End If
End If
End Sub
The table I'm trying to export (Export_tbl) exists and is editable (not read only), and I can manually export it without issue. I'm guessing this may be an issue with the machine I'm on, with permissions or something? Or am I using the filedialog reference incorrectly? Thanks for any help.
The problem was that I failed to properly assign a full file name for the table being exported---you need to include the file path, name, AND extension (at least in this case, since I'm trying to export as text/CSV). The following worked:
Private Sub Export_Run()
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogSaveAs)
If fd.Show = True Then
If Format(fd.SelectedItems(1)) <> vbNullString Then
thename = fd.SelectedItems(1) & ".csv"
DoCmd.TransferText acExportDelim, , "Export_tbl", thename, False
End If
End If
End Sub
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
I am trying to output a report as a text file, using a specific file name and path. Below is what I am currently using and when it runs, it receive a window prompting me for the file location and name.
When I comment out "strFileName = Me.Field1" and remove the ' from the line below, it exports the file with no issues. The value of Field1 is exactly what is used in the 2nd line.
Private Sub ExportFlatFile_Click()
DoCmd.SetWarnings (WarningsOff)
DoCmd.OpenQuery "xx-FlatFile-1Delete"
DoCmd.OpenQuery "xx-FlatFile-AdminFee"
DoCmd.OpenQuery "xx-FlatFile-BF"
DoCmd.OpenQuery "xx-FlatFile-CO"
DoCmd.OpenQuery "xx-FlatFile-FFee"
DoCmd.OpenQuery "xx-FlatFile-Fuel"
DoCmd.OpenQuery "xx-FlatFile-Insp"
DoCmd.OpenQuery "xx-FlatFile-Lift"
DoCmd.OpenQuery "xx-FlatFile-PI"
DoCmd.OpenQuery "xx-FlatFile-Pump"
DoCmd.OpenQuery "xx-FlatFile-APump"
DoCmd.OpenQuery "xx-FlatFile-0DeleteFileName"
DoCmd.OpenQuery "xx-FlatFile-1CreateFileName"
Dim strFileName As String
strFileName = Me.Field1
'strFileName = "\\Mis-fs2\imsi2\Billing Databases\APL\WESEDI-999-198-20170119-01.txt"
DoCmd.OutputTo acOutputReport, "rptFlatFile", acFormatTXT, strFileName, False, , , acExportQualityPrint
DoCmd.SetWarnings (WarningsOn)
End Sub
The '.' operator is for built-in (system) fields. The '!' operator is for named or user created fields.
You should use: Me!Field1
Most built in functions will bring up this kind of dialog when they can't locate the specified object.
I got the following VBA code from the web a while ago:
Private Sub btnCreatePDF_Click()
Dim MyPath As String
Dim MyFilename As String
MyPath = "D:\reports\"
MyFilename = "KS1.pdf"
'Open report preview and auto-save it as a PDF
DoCmd.OpenReport "Rpt_KS1", acViewPreview
DoCmd.OutputTo acOutputReport, "", acFormatPDF, MyPath & MyFilename, False 'Change false to true here to auto-open the saved PDF
'Close the previewed report
DoCmd.Close acReport, "Rpt_KS1"
End Sub
It was for use in MS Access to create a single pdf of reports (containing up to 30 pages) and works fine for what i needed. However, i now need to split the report into the 30 or so pages and create a pdf for each of the pages. Any idea how this can be done?
I have a 'username' in the report or can add a unique ID if this helps to split them etc.
Use the 4th parameter (WhereCondition) of Docmd.OpenReport. With the WhereCondition, do exactly what you would normally do when adding a Where to your query, only don't include the word Where. This will make the report only display records that match the WhereCondition.
Retrieve your list of unique identifiers into some sort of a collection, or recordset then do a loop. This example assumes that you have them in a collection called uniqueIds and will almost definitely require some modification by you.
Dim MyPath As String
Dim MyFilename As String
MyPath = "D:\reports\"
'Loop structure may vary depending on how you obtain values
For each uniqueId in uniqueIds
MyFilename = "KS1" & uniqueId & ".pdf"
'Open report preview and auto-save it as a PDF
DoCmd.OpenReport "Rpt_KS1", acViewPreview, , "uniqueField = " & uniqueID
DoCmd.OutputTo acOutputReport, "", acFormatPDF, MyPath & MyFilename, False
'Close the previewed report
DoCmd.Close acReport, "Rpt_KS1"
Next uniqueId
Strictly speaking, this may not result in a different PDF for each page. But it will generate a different PDF for each uniqueID, which might be every page depending on your data.