I'm using code below to make whatever the record source is an excel spreadsheet - two functions are to work together and make it easier for me to do export to.
I can't find the fault in the error. I have this picking out multiple subforms and I get errors or the wrong recordsource (if it doesn't delete the original object querydef it uses the same one over for some reason)
help :O
Code:
'save as dialog box
Public Function SaveAsLocation(Optional filename As String) As String
Dim strButtonCaption As String
Dim strDialogTitle As String, strfilename As String
'Define your own Captions if necessary
strButtonCaption = "Select a Folder"
strDialogTitle = "Folder Selection Dialog"
If Not IsMissing(filename) Then
strfilename = filename
Else
strfilename = ""
End If
With Application.FileDialog(msoFileDialogSaveAs)
.ButtonName = strButtonCaption
.InitialView = msoFileDialogViewDetails 'Detailed View
.title = strDialogTitle
.InitialFileName = strfilename
If .SHOW Then
SaveAsLocation = .SelectedItems(1) 'Write Folder Path to Field
End If
End With
End Function
Code:
'gives you excel of records
Public Sub ExportToExcel(RecordSource As String, filename As String)
If FindQuery("QueryExportToExcel") Then
CurrentDb.QueryDefs.Delete "QueryExportToExcel"
End If
Dim qryname As String
Dim qdfNew As QueryDef
On Error GoTo ErrorHandler
Dim strSave As String
strSave = SaveAsLocation(filename)
qryname = "QueryExportToExcel"
Set qdfNew = CurrentDb.CreateQueryDef(qryname, RecordSource)
Debug.Print strSave
DoCmd.TransferSpreadsheet acExport, 8, qryname, strSave & ".xls", True
Debug.Print RecordSource
CurrentDb.QueryDefs.Delete qdfNew.Name 'cleanup
ErrorHandler:
Resume Next
End Sub
Code:
'find query
Function FindQuery(strQueryName) As Boolean
Dim dbs As dao.Database
Dim found As Boolean
Set dbs = CurrentDb
On Error GoTo fail
'next line succeeeds without error if qry exists
found = Len(dbs.QueryDefs(strQueryName).Name) > 0
exithere:
FindQuery = found
fail:
'no query of that name
found = False
Resume exithere
End Function