2013-04-25 81 views
-1

我现在有下面这节省了两个数据表到Excel工作簿中的两个独立的表,然后将代码打开工作簿:访问VBA:导出表到Excel 2010数据透视表

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中显示数据,但我不确定如何做到这一点 - 任何人都可以帮忙吗? :-)

+0

你是什么意思的“格式电子表格成一个数据透视表“?你想创建一个基于数据表的数据透视表吗? – Barranka 2013-04-25 21:29:20

+0

这可能是我想要做的,但我可能有术语错误 - 基本上我希望代码运行,以便在Excel打开时显示数据透视表中的导出数据。谢谢。 – duney 2013-04-25 21:32:53

+0

好吧,让我试试另一种方式:你是否想根据表中已有的数据创建数据透视表,或者想要逐格格式化数据以显示某些内容*数据透视表? – Barranka 2013-04-25 21:44:21

回答

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 
... 

希望这有助于你

+0

我正在使用此代码,但是没有任何事情发生,代码成功运行,Excel文件已成功创建,但数据透视表未在工作表中进行。我首先填充源数据,然后尝试创建数据透视表。源数据已创建,但未创建数据透视表。任何想法为什么? – 2015-07-04 13:44:47

0

不知道如果你终于找到它,但是,在我的代码,如果我使用position和xlrow/column字段,也不会发生任何事情。 我摆脱了他们,只使用.lientation = 1为xlcolumnfield,2为xlrowfield,3为过滤和4为AddDataField。 我没有声明职位,Excel本身根据我编写代码的顺序调整职位。 说,我反而坚持公式:我无法将其从计数改为总和;我尝试只重命名的价值,似乎工作,因为在字段列表中显示“总和...”,但在数据透视本身,我仍然得到计数...