数据透视表计算项目产生错误

时间:2017-02-28 23:11:44

标签: excel vba excel-vba

我有两个不同的工作表(Input1和Input2),我正在编写一段代码来构建报告。我的代码在Input1 - 工作表上成功运行,但在输入2 - 工作表上没有运行。

这是我的数据 - 输入1

Model       Date      Product     Payment   Mode
Blackberry  1/31/2010   Watch     Card      Online
Blackberry  2/1/2010    TV        Card      Online
Blackberry  1/31/2010   Watch     Cash      Online
Blackberry  2/3/2010    TV        Card      Online
Blackberry  2/4/2010    TV        Cash      Online
Blackberry  1/31/2010   Mobile    Cash      Store
Apple       2/6/2010    HeadPhone Cash      Store
Apple       1/31/2010   Watch     Cash      Store
Apple       2/8/2010    Watch     Cash      Store

我正在尝试构建一个使用两个计算字段的数据透视表。

  • 卖家1只添加手机和耳机
  • 卖家2增加了电视和手表。

在Input2中,我没有耳机。因此,适用于Input1的代码无效。

     Cells.Select
        ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
            "Input1!R1C1:R1048576C5", Version:=xlPivotTableVersion12).CreatePivotTable _
            TableDestination:="Output1!R8C2:R20C14", TableName:="PivotTable2", _
            DefaultVersion:=xlPivotTableVersion12
        Sheets("Output1").Select

        With ActiveSheet.PivotTables("PivotTable2").PivotFields("Product")
            .Orientation = xlColumnField
            .Position = 1
        End With

ActiveSheet.PivotTables("PivotTable2").AddDataField 
ActiveSheet.PivotTables( _
            "PivotTable2").PivotFields("Model"), "Count of Model", xlCount
        Range("C9").Select    ActiveSheet.PivotTables("PivotTable2").PivotFields("Product").CalculatedItems. _
            Add "Seller1", "=Mobile +HeadPhone", True


ActiveSheet.PivotTables("PivotTable2").PivotFields("Product").CalculatedItems. _
        Add "Seller2", "=Watch +TV", True
    With ActiveSheet.PivotTables("PivotTable2").PivotFields("Product")
        .PivotItems("HeadPhone").Visible = False
        .PivotItems("Mobile").Visible = False
        .PivotItems("TV").Visible = False
        .PivotItems("Watch").Visible = False
        .PivotItems("Watch ").Visible = False
        .PivotItems("(blank)").Visible = False
    End With

    End Sub

这是我要找的输出 - Output Required

1 个答案:

答案 0 :(得分:1)

只是“.PivotItems('HeadPhone')。Visible = False”是否正在创建错误?最简单的解决方法是不包括此项。但是,通过一些调整,您可以使代码更具动态性:

        Dim wb as Workbook

        ' Use variables, they are more accurate and it helps make your code
        ' more dynamic.
        Dim wsIn_1 as Worksheet, wsIn_2 as Worksheet, _
        wsOut_1 as Worksheet, wsOut_2 as Worksheet

        Dim pt1 as PivotTable, pt2 as PivotTable

        ' For use in looping pivotitems if you need to
        Dim pi as PivotItem


        Dim sCalculate as String

        ' Set it however you wish, this just prompts the user.
        sCalculate = Inputbox("Please enter the formula you would like to use.")
        ' Assumes that workbook running code is the same one being edited.
        Set wb = ThisWorkbook

        ' Set the worksheet variables
        With wb
            Set wsIn_1 = .Sheets("Input1")
            Set wsIn_2 = .Sheets("Input2")
            Set wsOut_1 = .Sheets("Output1")
            Set wsOut_2 = .Sheets("Output2")
        End With

        ' Always name your pivot tables. It is good practice. In this case
        ' I created a generic name but you can make something more precise.
        wb.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
            "Input1!R1C1:R1048576C5", Version:=xlPivotTableVersion12).CreatePivotTable _
            TableDestination:="Output1!R8C2:R20C14", TableName:="pt_Output_1", _
            DefaultVersion:=xlPivotTableVersion12

        ' It is best to avoid activate and select, but I am including it
        ' in case it is somehow important for the sheet to be active on the
        ' so you can see the code running. No need to activate it just to work
        ' on it though.
        wsOut_1.Activate

        With wsOut_1.PivotTables("pt_Output_1").PivotFields("Product")
            .Orientation = xlColumnField
            .Position = 1
        End With

        Set pt2 = wsOut_1.PivotTables("PivotTable2")

        With pt2
            .AddDataField 
            .PivotFields("Model"), "Count of Model", xlCount    
            ' All you need to do is replace the string within the code with a string variable
            ' It would be ideal to have some kind of data validation in here to ensure
            ' only valid strings can be passed in. You will also need to somehow ensure
            ' that you are entering an appropriate formula.
            .PivotFields("Product").CalculatedItems.Add "Seller1", sCalculate, True
            .PivotFields("Product").CalculatedItems.Add "Seller2", "=Watch +TV", True


            ' I commented out the entire block below since I dont think this
            ' is what you are trying to accomplish. Instead use this:

            .PivotFields("Product").Visible = xlHidden

            ' With .PivotFields("Product")
                ' Since it looks like you are simply hiding everything
                ' use a for loop instead.

                ' I have made kept all of this commented out because
                ' because you will run into an error if there isn't at
                ' least one visible item.

                ' For each pi in .PivotItems
                '     pi.Visible = False
                ' Next
                ' .PivotItems("HeadPhone").Visible = False
                ' .PivotItems("Mobile").Visible = False
                ' .PivotItems("TV").Visible = False
                ' .PivotItems("Watch").Visible = False
                ' .PivotItems("Watch ").Visible = False
                ' .PivotItems("(blank)").Visible = False
           ' End With
        End With

    End Sub