访问VBA:将表导出到Excel 2010数据透视表

时间:2013-04-25 21:25:19

标签: excel vba ms-access access-vba excel-2010

我目前有以下代码,它将两个数据表保存到两个单独的工作表上的Excel工作簿中,然后打开工作簿:

Dim outputFileName As String
Dim outputFile As String
outputFile = "Export_" & Format(Date, "yyyyMMdd") & Format(Time, "_hhmm") & ".xlsx"
outputFileName = CurrentProject.Path & "\" & outputFile
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "Callouts", outputFileName, True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "Members", outputFileName, True

'Load Excel
Set appExcel = New Excel.Application
Set wbkOutput = appExcel.Workbooks.Open(outputFileName)

'Show excel window
appExcel.Visible = True

我想添加一些代码来创建一个数据透视表来显示excel中的数据,但我不确定如何做到这一点 - 有人可以帮忙吗? : - )

1 个答案:

答案 0 :(得分:0)

以下是创建数据透视表的示例代码:

...
Dim aSheet as Worksheet
Set aSheet = ThisWorkbook.Sheets.Add
ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
                                SourceData:="Sheet1!A1:D1000",
                                Version:=xlPivotTableVersion12). _
    CreatePivotTable TableDestination:=aSheet.Name&"!A1", _
                     TableName:="YourPivotTable", _
                     DefaultVersion:=xlPivotTableVersion12
ThisWorkbook.Sheets(aSheet.Name).Select
' Add the column field (the name of the pivot field is one of your data table) '
With ActiveSheet.PivotTables("YourPivotTable").PivotFields("columnHeaderField")
    .Orientation = xlColumnField
    .Position = 1
End With
' Add the row field (the name of the pivot field is one of your data table) '
With ActiveSheet.PivotTables("YourPivotTable").PivotFields("rowHeaderField")
    .Orientation = xlRowField
    .Position = 1
End With
' Add the data field
With ActiveSheet.PivotTables("YourPivotTable")
    .AddDataField .PivotFields("aValueField"), "Sum of a value", xlSum
    .AddDataField .PivotFields("anotherValueField"), "Sum of another value", xlSum
End With
...

希望这有助于你