I am using a button on an access form to export a report using a custom Excel Template.
However, if the excel file is open when a user tries to save, it will throw an error, then nothing happens, but the excel template file stays open in the background, causing the user to have to manually close it through the task manager.
Also, currently you can save the workbook as anything.
For instance I can overwrite a word file, which is tacky. How can I get it to only save as .xls or .xlsx file types?
Code:
Option Compare Database
Public Sub btn_Export_Click()
Dim objXL As Object
Dim xlWB As Object
Dim xlWS As Object
Dim rst As DAO.Recordset
Dim fd As FileDialog
Dim vrtSelectedItem As Variant
Set objXL = CreateObject("Excel.Application")
'Opens the Template to Put records into.
Set xlWB = objXL.Workbooks.Open("C:\Users\xxxxx\Desktop\Test Database\2013 Excel Workbook Test")
'chooses which worksheet to put the data into.
Set xlWS = xlWB.Worksheets("xDetails")
'Selects which Query to retrieve the data from to export.
Set rst = CurrentDb.OpenRecordset("qry_ReportOutput")
'Create a FileDialog Object as a SaveAs Dialog Box
Set fd = Application.FileDialog(msoFileDialogSaveAs)
xlWS.Range("B3").CopyFromRecordset rst
With fd
If .Show = -1 Then
For Each vrtSelectedItem In .SelectedItems
xlWB.SaveAs vrtSelectedItem
Next vrtSelectedItem
Else
End If
End With
Set fd = Nothing
rst.Close
Set rst = Nothing
xlWB.Close
End Sub
Ideally, I want it to look like this.
Code:
With fd
If .Show = -1 Then
For Each vrtSelectedItem In .SelectedItems
If blnWorkbookopen = 0 then
xlWB.SaveAs vrtSelectedItem (only as a workbook file type)
else
msgbox "Please close the Workbook you are trying to save to."
Set fd = Nothing
rst.Close
Set rst = Nothing
xlWB.Close
Exit Sub
Next vrtSelectedItem
Else
End If
End With
Thanks!