VBA数据透视表出现在特定工作表上

时间:2015-10-26 06:37:49

标签: excel vba excel-vba pivot-table

目前我有这个代码,它运行顺利。但是,创建的Pivot似乎没有出现在" ST_TicketPivot"我创建的工作表。

那么,我怎样才能让Pivot出现在我想要的表格上?

Private Sub ST_Tickets()
    Dim objTable As PivotTable, objField As PivotField
    ActiveWorkbook.Sheets("Paste Record").Select
    Range("A1").Select

    Sheets.Add.Name = "ST_TicketsPivot"
    Sheets("ST_TicketsPivot").Activate


    Set objTable = Sheet1.PivotTableWizard
    objTable.PivotCache.MissingItemsLimit = xlmissingItemNone
    objTable.PivotCache.Refresh

    Set objField = objTable.PivotFields("Priority")
    objField.Orientation = xlColumnField

    Set objField = objTable.PivotFields("Status")
    objField.Orientation = xlRowField

    Set objField = objTable.PivotFields("Contact Name") ' change with type
    objField.Orientation = xlRowField

    Set objField = objTable.PivotFields("Salesforce Case Number")
    objField.Orientation = xlDataField
    objField.Function = xlCount

End Sub

1 个答案:

答案 0 :(得分:1)

这是因为PivotWizard创建了一个用于放置数据透视表的新工作表,因此您必须使用objTable.Parent.Name对其进行重命名。

尝试一下:

Private Sub ST_Tickets()
    Dim objTable As PivotTable, objField As PivotField, Ws As Worksheet
    ActiveWorkbook.Sheets("Paste Record").Range("A1").Select

    Set Ws = Sheets.Add
    Ws.Name = "ST_TicketsPivot"

    Set objTable = Sheet1.PivotTableWizard(TableDestination:=Ws.Cells(3, "A"))
    objTable.PivotCache.MissingItemsLimit = xlmissingItemNone
    objTable.PivotCache.Refresh

    Set objField = objTable.PivotFields("Priority")
    objField.Orientation = xlColumnField

    Set objField = objTable.PivotFields("Status")
    objField.Orientation = xlRowField

    Set objField = objTable.PivotFields("Contact Name") ' change with type
    objField.Orientation = xlRowField

    Set objField = objTable.PivotFields("Salesforce Case Number")
    objField.Orientation = xlDataField
    objField.Function = xlCount

End Sub