确定工作表中值的范围并将其粘贴到不同的工作表中

时间:2016-07-11 16:25:10

标签: excel-vba pivot-table vba excel

我有一个数据透视表,其行号可能会根据数据而改变。我想复制数据透视表并将其粘贴为从另一个现有工作表中的B列开始的值。

为此,我首先尝试使用以下代码获取数据透视表的名称并将其存储在命名范围内:

Sub ListPivotsInfor()
    Dim St As Worksheet
    Dim NewSt As Worksheet
    Dim pt As PivotTable
    Dim I, K As Long
    Application.ScreenUpdating = False
    Set NewSt = Worksheets.Add
    ActiveSheet.Name = "ListOfPivotTables"
    I = 1: K = 2
    With NewSt
        .Cells(I, 1) = "Name"
        .Cells(I, 2) = "Sheet"
        .Cells(I, 3) = "Location"
        For Each St In ActiveWorkbook.Worksheets
            For Each pt In St.PivotTables
                I = I + 1
                .Cells(I, 1).Value = pt.Name
                .Cells(I, 2).Value = St.Name
                .Cells(I, 3).Value = pt.TableRange1.Address
            Next
        Next
        .Activate
    End With
    Application.ScreenUpdating = True

Dim cell As Range
Dim rng As Range
Dim RangeName As String
Dim CellName As String

'Single Cell Reference (Workbook Scope)
  RangeName = "PivotName"
  CellName = "A2"

  Set cell = Worksheets("ListOfPivotTables").Range(CellName)
  ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell

我后来尝试使用以下代码复制数据透视表并将其粘贴到另一个工作表中:

Worksheets.Add
  ActiveSheet.Name = "GEP"

  Worksheets("GEP Write").PivotTables(PivotName).TableRange2.Copy Destination:=Worksheets("GEP").Range("B1")

最后一行是抛出"运行时错误1004:无法获取工作表类的#PtttoTables属性"。

感谢任何帮助。

此致

0 个答案:

没有答案