[英]MS Access VBA to export a filtered form to excel
这是一个困扰我大约一个月的问题...
我有一个允许用户过滤记录的表单,很简单。 但我想让他们选择将过滤后的记录导出到 Excel。 我不想使用 docmd.outputTo 因为它不会过滤记录,它将所有记录放在文件中。 我环顾四周,发现了一些代码,但问题是它在表单上输出了所有内容。 我的目标是将 output 过滤后的数据转换为新的 excel 表。 但我仍然很新,并且在代码中苦苦挣扎。 我附上了错误的图像(下)和代码感谢您的帮助在此处输入图像描述
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
您可以使用表单中的过滤器作为查询条件,也可以将该查询导出到 excel。 它只会导出过滤的记录。
是的,正是。 这基本上是 Hira Iftikhar 所说的,看起来像这样。
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
访问视图:
Excel 之前:
Excel 之后:
单击表单>添加按钮>单击按钮并单击“确定”然后单击“取消”>右键单击该按钮并单击“构建事件”>单击“代码生成器”>最后...粘贴我给的代码您进入打开的 Window。 进行一些非常小的更改(应该很明显......点击事件的名称)。 现在,您应该对 go 很好。 如果您有其他问题,请回帖!! 否则,请更新我的答案以承认这对其他人有帮助。 谢谢!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.