在excel中转​​置

时间:2014-09-12 12:31:46

标签: excel vba excel-vba

我有一个数据集

2011 A 560

2011 B 349

2012 A 456

2012 B 789

输出:

      A   B
2011 560 349

2012 456 789

我想手动使用excel,也可以通过vba。任何帮助表示感谢。

2 个答案:

答案 0 :(得分:0)

IFF是你的数据集的样子。

选择所有数据并插入数据透视表。 将行设置为第一列(具有年份的行) 将列设置为第二列(具有A或B的列) 将您的值设置为第三列(具有数字的列)的平均值

答案 1 :(得分:0)

首先提供数据标题

data with headers

从数据中创建数据透视表

Sub PivotData()
    Dim PivotSource As Range
    Dim PivotName As String
    Dim PivotDest As Range


    PivotName = "PivotTable1"
    Set PivotSource = Sheets("Sheet1").UsedRange
    Set PivotDest = Sheets("Sheet2").Range("A1")

    'Select the sheet containing data
    Sheets(PivotSource.Parent.Name).Select

    'Create a pivot cache out of the data
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
                                      SourceData:=PivotSource, _
                                      Version:=xlPivotTableVersion14).CreatePivotTable _
                                      TableDestination:=PivotDest, _
                                      TableName:=PivotName, _
                                      DefaultVersion:=xlPivotTableVersion14

    'Select the destination Sheet
    Sheets(PivotDest.Parent.Name).Select

    'Create the pivot table
    With ActiveSheet.PivotTables(PivotName)
        .PivotFields("Year").Orientation = xlRowField
        .PivotFields("Year").Position = 1
        .AddDataField .PivotFields("Value"), "Sum of Value", xlSum
        .PivotFields("Type").Orientation = xlColumnField
        .PivotFields("Type").Position = 1
        .RowGrand = False
        .ColumnGrand = False
    End With

    'Convert the pivot table to a range
    Cells.Copy
    Cells.PasteSpecial Paste:=xlPasteValues, _
                       Operation:=xlNone, _
                       SkipBlanks:=False, _
                       Transpose:=False

    'Remove the pivot table header
    Rows(1).Delete
    Range("A1").ClearContents

    ActiveSheet.UsedRange.Columns.AutoFit
    Range("A1").Select
End Sub

结果:

Pivoted Data

相关问题