使用VBScript创建数据透视表

时间:2016-08-26 08:24:38

标签: vbscript pivot pivot-table

我正在尝试使用VBScript创建数据透视表。我认为我已接近实现它,但我不知道如何创建报告过滤器并为"内部"设置过滤器,或者如何在值中使用sum而不是count。

这就是我现在所拥有的:

xlA1 = 1
xlDatabase = 1
xlRowField = 1
xlColumnField = 2
xlFilterField = 3

Set xlBook1 = objExcel.WorkBooks.Open(ws_path &  "FINAL.xlsx")
set rngData =xlBook1.Sheets("NONPO").Usedrange
set rngReport = xlBook1.Sheets("NONPO").Range("CE1")

set pvtCache = xlBook1.pivotCaches.add(xlDatabase, rngData.address(true, true, xlA1, true))
set pvtTable = pvtCache.createPivotTable(rngReport, "Pivot1")

pvtTable.pivotFields("Date").orientation =xlRowField
pvtTable.pivotFields("Country Code").orientation = xlColumnField
pvtTable.pivotFields("Agent Type").orientation =  xlFilterField
 '*****Here I should Use filter as "Internal"*****

pvtTable.pivotFields("Hours").orientation = xlsum  *****xlsum is not working*****

2 个答案:

答案 0 :(得分:0)

我相信这就是你想要的。

pt.AddDataField(pt.PivotFields("Hours"), "Hours", _
    Excel.XlConsolidationFunction.xlSum)

所以,整个事情应该看起来像这样(根据你的具体需要进行修改)。

Private Sub CreatePivotTable(tableName As String)
    Dim targetSheet As Excel.Worksheet = ExcelApp.Sheets.Add
    Dim ptName As String = "MyPivotTable"

    'We'll assume the passed table name exists in the ActiveWorkbook
    targetSheet.PivotTableWizard(Excel.XlPivotTableSourceType.xlDatabase, _
        tableName, targetSheet.Range("A5"))
    targetSheet.Select()

    Dim pt As Excel.PivotTable = targetSheet.PivotTables(1)

    'To be professional or merely resuable, the name could be passed as parameter
    With pt.PivotFields("Order Date")
        .Orientation = Excel.XlPivotFieldOrientation.xlRowField
        .Position = 1
    End With

    pt.AddDataField(pt.PivotFields("Order Total"), "Order Count", _
        Excel.XlConsolidationFunction.xlCount)
    pt.AddDataField(pt.PivotFields("Order Total"), "Total for Date", _
        Excel.XlConsolidationFunction.xlSum)

    '--OR--
    'AddPivotFields(pt, "Order Total", "Order Count", _
    '   Excel.XlConsolidationFunction.xlCount)
    'AddPivotFields(pt, "Order Total", "Total For Date", _
    '   Excel.XlConsolidationFunction.xlSum)

    Marshal.ReleaseComObject(pt)
    Marshal.ReleaseComObject(targetSheet)
End Sub

答案 1 :(得分:0)

应该像这样......

    With pvtTable.pivotFields("Hours")
    .orientation = 4
    .Function = xlSum
    End With