Ошибка выполнения 1004: невозможно получить свойство PivotTables класса Worksheet - PullRequest
0 голосов
/ 15 января 2019

Я новичок в Excel VBA и пытаюсь создать сводную таблицу, используя только поле строк со следующими кодами, но обнаружил ошибку 1004, и мне потребуется помощь в устранении ошибок.

Я указал ошибку в кодах сразу после комментариев // Макросы выше создают сводный кеш и адрес для вставки новой сводной таблицы // для легкой ссылки.

Ценю любую помощь по этому вопросу.

Sub getpivotUI2()    
    '**strong text**    
    ' getpivotUI2 Macro    
    ' Create PivotTable from Task_Sheet to filter duplicate bill (UI2)    
    '

    Dim P2Sheet, TSheet As Worksheet    
    Dim P2Cache As PivotCache    
    Dim P2Table As PivotTable    
    Dim P2Range As Range    
    Dim L2Row, L2Col As Long   

    ' Declaring the variables above

    Set TSheet = Worksheets("Task_Sheet")    
    Set P2Sheet = Worksheets("pivot_UI2")   

    L2Row = TSheet.Cells(Rows.Count, 1).End(xlUp).Row    
    L2Col = TSheet.Cells(4, Columns.Count).End(xlToLeft).Column

    Set P2Range = TSheet.Cells(4, 1).Resize(L2Row, L2Col)

    'Macros above determine where the cursor is referenced

    P2Sheet.Cells.Delete 'Removing all previous data the pivotTable worksheet
    Set P2Cache = ActiveWorkbook.PivotCaches.Create _    
      (SourceType:=xlDatabase, SourceData:=P2Range)

    Set P2Table = P2Cache.CreatePivotTable _    
      (TableDestination:=P2Sheet.Cells(3, 1), TableName:="PivotTableUI2")

    'Macros above create a pivot cache and address to insert the new pivot table     

    With ActiveSheet.PivotTables("PivotTableUI2").PivotFields("UI2") '**<-- ERROR OCCURANCE**   
        .Orientation = xlRowField
        .Position = 1
    End With           

    With ActiveSheet.PivotTables("PivotTableUI2").PivotTables("PivotTableUI2").PivotFields("Count_UI2")
        .Orientation = xlDataField
        .Function = xlCount
        .Name = "Count of UI2"
    End With

    With ActiveSheet.PivotTables("PivotTableUI2").PivotTables("PivotTableUI2").PivotFields("R Patient" & Chr(10) & "Count")
        .Orientation = xlDataField
        .Function = xlCount
        .Name = "Count of R Patient"
    End With

    With ActiveSheet.PivotTables("PivotTableUI2").PivotTables("PivotTableUI2").PivotFields("PR Patient" & Chr(10) & "Count")
        .Orientation = xlDataField
        .Function = xlCount
        .Name = "Count of PR Patient"
    End With

    'Macros above inserts a row field and data field in the pivot table
End Sub

1 Ответ

0 голосов
/ 15 января 2019

Попробуйте код ниже, объяснение внутри комментариев кода

Option Explicit

Sub getpivotUI2()

    ' getpivotUI2 Macro
    ' Create PivotTable from Task_Sheet to filter duplicate bill (UI2)

    Dim P2Sheet As Worksheet, TSheet As Worksheet
    Dim P2Cache As PivotCache
    Dim P2Table As PivotTable
    Dim P2Range As Range
    Dim L2Row As Long, L2Col As Long

    ' Declaring the variables above

    Set TSheet = ThisWorkbook.Worksheets("Task_Sheet")
    Set P2Sheet = ThisWorkbook.Worksheets("pivot_UI2")

    With TSheet
        L2Row = .Cells(.Rows.Count, 1).End(xlUp).Row
        L2Col = .Cells(4, .Columns.Count).End(xlToLeft).Column

        Set P2Range = .Range(.Cells(4, 1), .Cells(L2Row, L2Col)) ' set the data source of the Pivot-Cache
    End With

    'Macros above determine where the cursor is referenced

    P2Sheet.Cells.Delete 'Removing all previous data the pivotTable worksheet

    ' set the Pivot-Cache object
    Set P2Cache = ActiveWorkbook.PivotCaches.Add(xlDatabase, P2Range.Address(0, 0, xlA1, xlExternal))

    ' set the Pivot-Table object
    Set P2Table = P2Sheet.PivotTables.Add(PivotCache:=P2Cache, TableDestination:=P2Sheet.Range("A3"), TableName:="PivotTableUI2")

    'Macros above create a pivot cache and address to insert the new pivot table

    ' ~~~ For Debug Only ~~~
    Dim PTFld As PivotField

    For Each PTFld In P2Table.PivotFields
        Debug.Print PTFld.Name
    Next PTFld

    With P2Table.PivotFields("UI2")
        .Orientation = xlRowField
        .Position = 1
    End With

    ' rest of your Pivot-Fields code …

End Sub

Я добавил в Sub раздел, который гарантирует, что в вашей сводной таблице есть поле " U12 ".

Когда вы запустите эту часть:

' ~~~ For Debug Only ~~~
Dim PTFld As PivotField

For Each PTFld In P2Table.PivotFields
    Debug.Print PTFld.Name
Next PTFld

В ближайшем окне вы должны получить следующее значение:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...