如何选择一些选定的数据透视表区域?

时间:2013-02-13 09:10:49

标签: vba excel-vba excel

我正在尝试选择并复制数据透视表的某些选定区域。我能够确定我想要的区域数量,并且能够在消息框中显示该范围,这不是我的目标。我想要复制选定的范围。我的代码看起来像这样。 我想复制范围内的值(toprow1,leftcoloumn:lastrow,rightcoloumn)。 FYI消息框代码是我不需要的东西它只是告诉你Range no。

    Sub PivotTableRangeAreas()

    With ActiveSheet.PivotTables(1)

  Dim TopRow1 As Long, TopRow2 As Long, LastRow As Long
  Dim LeftColumn As Long, RightColumn As Long

  TopRow2 = .TableRange2.Row
  With .TableRange1
  TopRow1 = .Row
  LastRow = .Rows.Count + .Row - 1
  LeftColumn = .Column
  RightColumn = .Columns.Count + .Column - 1
  End With

  MsgBox "The pivot table named " & .Name & vbCrLf & _
  "occupies these range elements:" & vbCrLf & vbCrLf & _
  "With the Report (Page) field: " & vbCrLf & _
  .TableRange2.Address(0, 0) & vbCrLf & _
  "Without the Report (Page) field: " & vbCrLf & _
  .TableRange1.Address(0, 0) & vbCrLf & vbCrLf & _
  "First row, with the Report (Page) field: " & TopRow2 & vbCrLf & _
  "First row, without the Report (Page) field: " & TopRow1 & vbCrLf & _
  "Last row: " & LastRow & vbCrLf & _
  "Left column: " & LeftColumn & vbCrLf & _
  "Right column: " & RightColumn, , "Pivot table location."

  End With

  End Sub

1 个答案:

答案 0 :(得分:1)

我猜测它只是你要复制的值吗?如果是这样,尝试从这样的东西开始 - 它将值放入Sheet2,从范围A1开始。我不确定您要将数据透视表中的哪个范围复制到哪里 - 您必须更改其中一些以适应:

Sub CopyRange()

Dim vArray() As Variant

'Copies the values between (Toprow1, LeftColumn) and (LastRow, RightColumn) into an array
vArray = ActiveSheet.Range(Cells(TopRow1, LeftColumn), Cells(LastRow, RightColumn)).Value
'Pastes the values from the array into Sheet2, starting at A1
Sheet2.Range("A1").Resize(UBound(vArray, 1), UBound(vArray, 2)).Value = vArray

End Sub