简体   繁体   中英

MS Access VBA to export a filtered form to excel

Here's one that's been bugging me for about a month...

I have a form that allows users to filter records, simple enough. But I want to give them the option to export the filtered records to Excel. I don't want to use the docmd.outputTo due to it won't filter the records, it puts all of the records in the file. I've looked around and found some code, but the problem is that it outputs EVERYTHING on the form. My goal is to output the filtered data into a new excel sheet. But I am still very new and struggling with the code. I am attaching the image for the error (Below) and the code thanks for the help enter image description here

Private Sub cmdExport_Click()

Dim xlApp As Object
Dim xlBook As Object
Dim rs As DAO.Recordset
Dim sql As String
Dim i As Integer

Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add
 'This selects form

sql = Forms("ReportForm13").Form.RecordSource 'Your record source if not a subform
'Set rs = CurrentDb

For i = 1 To rs.Fields.Count
xlBook.Sheets(1).Cells(1, i) = rs.Fields(i - 1).Name 'Write Field names to Excel
Next i
xlBook.Sheets(1).Cells(2, 1).CopyFromRecordset rs 'Import the recordset data through Excel

' You can add whatever other formatting you want by running Excel VBA throught the xlApp object

xlApp.Visible = True

Set xlApp = Nothing
Set xlBook = Nothing
Set rs = Nothing
End Sub

You can use the filter in form as criteria in query and can instead export that query into excel. It will just export filtered records.

Yeah, exactly. It's basically what Hira Iftikhar said, and it looks like this.

Private Sub cboFilterIsCorporate_Click()

Dim strSQL As String
strSQL = Me.RecordSource
strSQL = "Select * From " & strSQL & " WHERE " & Me.Filter

With CurrentDb.QueryDefs("qryTest")
   .SQL = strSQL
End With

' now export the query  with critera to excel
Dim strOutFile As String

strOutFile = "C:\your_path\Test.xlsx"

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
      "qryTest", strOutFile, True

End Sub

Access View:

在此处输入图像描述

Excel Before:

在此处输入图像描述

Excel After:

在此处输入图像描述

click the form > add a button > click the button and click 'ok' then click 'cancel' > right-click the button and click 'Build Event' > click 'Code Builder' > finally...paste the code that I gave you into the Window that opens. Make a few very minor changes (should be obvious...the name of the click event). Now, you should be good to go,. Post back if you have additional questions!! Otherwise, please update my answer to acknowledge that this is helpful to others. Thanks!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM