将Access数据导出到Excel工作簿,并根据列值将数据拆分为多个工作表

时间:2015-09-09 16:24:01

标签: vba excel-vba ms-access access-vba export-to-excel

示例数据(名为' Pets_data_table'的本地访问表)

ID | Pet_Type | Pet_Owner

1      Dog        Jane Doe         
2      Cat        John Doe
3      Hamster    Bob Doe
4      Dog        Melissa Doe 
5      Cat        Aaron Doe

目前,我可以将此表中的数据导出到一个Excel工作簿,并根据特定字段的不同值将数据拆分为该Excel工作簿中的多个工作表。我使用以下VBA根据' Pet_Type'的不同值来分割数据。字段:

    Dim db As DAO.Database
    Set db = CurrentDb()
    Dim strPath As String
    strPath = "C:\Desktop\" & "Pets_dataset_export_" & format(date(),"yyyy-mm-dd") & ".xlsx" 
    DoCmd.TransferSpreadsheet acExport, 10, "Qry - Dog", strPath, True, "Dog"
    DoCmd.TransferSpreadsheet acExport, 10, "Qry - Cat", strPath, True, "Cat"
    DoCmd.TransferSpreadsheet acExport, 10, "Qry - Hamster", strPath, True, "Hamster"

    Set db = Nothing
    MsgBox "Export operation completed"

当我分割数据的字段具有少量不同值时,这表现良好。

但是,如果字段中存在大量不同的值,我希望将数据拆分,效率很低。

我想实现一种更动态的方法,允许我将数据集拆分为具有1 ... n个不同值的字段。

1 个答案:

答案 0 :(得分:1)

根据查询加载单个记录集,该查询为您提供独特的宠物类型...

SELECT DISTINCT p.Pet_Type
FROM Pets_data_table AS p;

然后遍历该记录集,将保存的查询( qryExportMe )更改为SELECT当前Pet_Type,然后导出查询...

Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strPath As String
Dim strSelectOneType As String
Dim strSelectPetTypes As String

' (change strPath back to what you need)
strPath = CurrentProject.Path & Chr(92) & "Pets_dataset_export_" & _
    Format(Date, "yyyy-mm-dd") & ".xlsx"
strSelectPetTypes = "SELECT DISTINCT p.Pet_Type" & vbCrLf & _
    "FROM Pets_data_table AS p;"

Set db = CurrentDb
Set rs = db.OpenRecordset(strSelectPetTypes, dbOpenSnapshot)
Do While Not rs.EOF
    strSelectOneType = "SELECT p.ID, p.Pet_Type, p.Pet_Owner" & vbCrLf & _
        "FROM Pets_data_table AS p" & vbCrLf & _
        "WHERE p.Pet_Type='" & rs!Pet_Type.Value & "';"
    Debug.Print strSelectOneType
    Set qdf = db.QueryDefs("qryExportMe")
    qdf.SQL = strSelectOneType
    qdf.Close
    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
        "qryExportMe", strPath, True, rs!Pet_Type.Value
    rs.MoveNext
Loop
rs.Close

请注意,代码要求保存的查询 qryExportMe 存在。但它的SQL属性并不重要,因为您每次都会通过主Do While循环更改它。