数据透视表 - VBA

时间:2016-11-03 11:14:04

标签: excel vba excel-vba pivot-table

我想创建一个数据透视表,可以通过选择获取信息的工作表来自动更新。我有40张ISO格式,我尝试了这个:

Sub tcd()
Dim CR As String
    CR = InputBox("Num of CR")
    Sheets(CR).Select
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        CR & "!" & Sheets(CR).Range("A1").CurrentRegion.Address(ReferenceStyle:=xlR1C1), _
        Version:=xlPivotTableVersion14).CreatePivotTable _
        TableDestination:="Feuil1!R2C2", TableName:="Sum", _
        DefaultVersion:=xlPivotTableVersion14
     Sheets("Feuil1").Select
     Cells(2, 2).Select
     Range("C8").Select
    With ActiveSheet.PivotTables("Sum").PivotFields( _
        "N1")
        .Orientation = xlRowField
        .Position = 1
    End With
    ActiveSheet.PivotTables("Sum").AddDataField ActiveSheet. _
        PivotTables("Sum").PivotFields("N2"), _
        "Num of N2", xlCount
    Sheets("SMM").Select
End Sub

不幸的是,它似乎无法运作,我无法找到原因,从而如何解决这个问题。

EDIT1:它给了我错误' 5' :无效的过程调用或参数。

编辑2:关于数据

Example

数据实际上包含6列,但只有前3列很重要。 我无法预测行数,因为它取决于将要使用的工作表。

如果您有任何想法? 我提前感谢你的答案!

1 个答案:

答案 0 :(得分:0)

阅读您的帖子,我假设您在InputBox中输入了工作表名称,因此 CR 是一个字符串,其中包含保存数据透视表数据的工作表名称。

(我从代码中删除了所有Select,无需创建您想要的PivotTable

Sub tcd()

Dim CR                  As String
Dim PTCache             As PivotCache
Dim PT                  As PivotTable
Dim wsSheet             As Worksheet
Dim PivotShtExists      As Boolean


CR = InputBox("Num of CR") ' assuming you enter the name of your worksheet's data in the input box

' check is "Feuil1" sheet already exists (from previous Macro runs)
For Each wsSheet In ThisWorkbook.Sheets
    If wsSheet.Name = "Feuil1" Then
        PivotShtExists = True
    End If
Next wsSheet

If Not PivotShtExists Then Sheets.Add.Name = "Feuil1"    

' add a new Pivot Cache
Set PTCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, CR & "!" & Sheets(CR).Range("A1").CurrentRegion.Address(ReferenceStyle:=xlR1C1))

' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PT = Sheets("Feuil1").PivotTables("Sum") ' check if "Sum" Pivot Table already created (in past runs of this Macro)

On Error GoTo 0
If PT Is Nothing Then

    ' create a new Pivot Table in "Feuil1" sheet
    Set PT = Sheets("Feuil1").PivotTables.Add(PivotCache:=PTCache, TableDestination:="Feuil1!R2C2", TableName:="Sum")

    With PT.PivotFields("N1")
        .Orientation = xlRowField
        .Position = 1
    End With

    PT.AddDataField PT.PivotFields("N2"), "Num of N2", xlCount

Else
    ' just refresh the Pivot cache with the updated Range
    PT.ChangePivotCache PTCache
    PT.RefreshTable
End If

End Sub