2013-05-01 4 views
2

Может ли кто-нибудь понять, почему этот код вызовет ошибку 1004 на последней строке? Все работает отлично до последней строки. У меня было это работает, тогда он начал получать эту ошибку, и я не могу понять, почему. Sheet2 - чистый лист. В настоящее время Sheet1 представляет собой только тестовые данные, 10 строк, 3 столбца. Он начинается с B3. У кого-нибудь есть идеи?Ошибка сводной таблицы 1004

Sub CreatePivot() 
     ' Define RngTarget and RngSource as Range type variables 
     Dim RngTarget As Range 
     Dim RngSource As Range 
     Dim intLastCol As Integer 
     Dim intCntrCol As Integer 

     ' RngTarget is where the PivotTable will be created (ie: Sheet2, Cell B3) 
     Set RngTarget = ThisWorkbook.Worksheets("Sheet2").Range("B3") 

     ' RngSource defines the Range that will be used to create the PivotTable 
     ' ActiveWorkbook = The currently opened Workbook 
     ' ActiveSheet = The currectly opened sheet 
     ' UsedRange = The Range of cells with active data in them 
     Set RngSource = ActiveWorkbook.ActiveSheet.UsedRange 

     ' Select the Range 
     RngSource.Select 

     ' Copy the Range into the clipboard 
     RngSource.Copy 

     ' Create a new PivotTable using the RngSource defined above, 
     ' in Excel format, 
     ' placed at the RngTarget location, 
     ' And name it PivotB3 just for reference if needed 
     ActiveWorkbook.PivotCaches.Create(xlDatabase, RngSource).CreatePivotTable RngTarget, "PivotB3" 

     ' Get the last used column from the data table 
     intLastCol = RngSource.Columns(RngSource.Columns.Count).Column 

     ' Select the Pivot table so we can apply the conditional formats 
     ActiveSheet.PivotTables("PivotB3").PivotSelect "", xlDataAndLabel, True 

ответ

1

Вы получаете ошибку, потому что в сводной таблице на sheet2, а не в ActiveSheet. Вы можете исправить ошибку, просто выбрав sheet2 перед выбором сводной таблицы, но то, что вы действительно хотите сделать, это исключить все варианты из вашего кода. См. Avoid Using Select для получения дополнительных пояснений/примеров.

Попробуйте это:

Sub CreatePivot() 
     Dim RngTarget As Range 
     Dim RngSource As Range 
     Dim ws As Worksheet 
     Dim pt As PivotTable 

     Set ws = ThisWorkbook.Sheets("Sheet2") 
     ws.Cells.Clear 
     ' RngTarget is where the PivotTable will be created (ie: Sheet2, Cell B3) 
     Set RngTarget = ws.Range("B3") 

     Set RngSource = ActiveWorkbook.ActiveSheet.UsedRange 

     ' Create a new PivotTable 
     ActiveWorkbook.PivotCaches.Create(xlDatabase, RngSource).CreatePivotTable _ 
      RngTarget, "PivotB3" 
     Set pt = RngTarget.PivotTable 

     ' We now have access to the pivot table and can modify as needed 
     pt.PivotSelect "", xlDataAndLabel, True 
     'ActiveSheet.PivotTables("PivotB3").PivotSelect "", xlDataAndLabel, True 
End Sub 

Примечание: Я удалены переменные и комментарии, которые не являются частью вашего вопроса, чтобы сделать его легче увидеть, что происходит.

+0

Спасибо! Эта ошибка исчезла. Теперь у меня есть еще 1004, хотя несколько строк прошло мимо предыдущего. Я уверен, что это нечто похожее. Следите за моей следующей записью. :) – user2021539

0

Try ниже код:

Sub CreatePivot() 
' Define RngTarget and RngSource as Range type variables 
    Dim RngTarget As Range 
    Dim RngSource As Range 
    Dim intLastCol As Integer 
    Dim intCntrCol As Integer 

    ' RngTarget is where the PivotTable will be created (ie: Sheet2, Cell B3) 
    Set RngTarget = ThisWorkbook.Worksheets("Sheet2").Range("B3") 

    ' RngSource defines the Range that will be used to create the PivotTable 
    ' ActiveWorkbook = The currently opened Workbook 
    ' ActiveSheet = The currectly opened sheet 
    ' UsedRange = The Range of cells with active data in them 
    Set RngSource = ActiveSheet.UsedRange 

    ' Select the Range 
    ' RngSource.Select 

    ' Copy the Range into the clipboard 
    ' RngSource.Copy 

    ' Create a new PivotTable using the RngSource defined above, 
    ' in Excel format, 
    ' placed at the RngTarget location, 
    ' And name it PivotB3 just for reference if needed 
    Dim oPC As PivotCache 
    Set oPC = ActiveWorkbook.PivotCaches.Create(xlDatabase, RngSource) 

    Dim oPT As PivotTable 
    Set oPT = oPC.CreatePivotTable(RngTarget, "PivotB3", True) 

    ' Get the last used column from the data table 
    intLastCol = RngSource.Columns(RngSource.Columns.Count).Column 

    ' Select the Pivot table so we can apply the conditional formats 
    'Worksheets("Sheet2").PivotTables("PivotB3").PivotSelect "", xlDataAndLabel, True 
End Sub 
Смежные вопросы