将扩展表格数据转换为扁平结构 - Excel VBA

问题描述 投票:0回答:1

我有一个扩展的数据表,我希望将其转换为扁平结构,以便我可以导入到固定的 SQL 格式表中。随着时间的推移,列数将继续扩大,我需要做的是在需要时引用不断扩大的行数,并将每月的列数引用到输出格式。对于 Excel VBA,我知道我需要 Sheet1 上数据的最后一行和最后一列,并且我需要循环行和列以最终将数据推送到 Sheet2 中最后一个单元格的结束范围。数据表结构示例如下。

enter image description here

excel vba transformation
1个回答
0
投票

这可以使用 Windows Excel 2010+ 和 Excel 365(Windows 或 Mac)中提供的 Power Query 来完成

使用 Power Query

  • 选择数据表中的某个单元格
  • Data => Get&Transform => from Table/Range
    from within sheet
  • PQ 编辑器打开时:
    Home => Advanced Editor
  • 记下第 2 行中的表名称
  • 将下面的 M 代码粘贴到您所看到的位置
  • 将第 2 行中的表名称更改回最初生成的名称。
  • 阅读评论并探索
    Applied Steps
    以了解算法

原始数据
enter image description here

M代码

let

Change Table name in next line to whatever your actual table name is in Excel
    Source = Excel.CurrentWorkbook(){[Name="Table3"]}[Content],

//Set the data types
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Deal", type text}, {"Data", Int64.Type}}
        & List.Transform(List.Skip(Table.ColumnNames(Source),2), each {_, type number})),

//Unpivot all except the first two columns
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"Data", "Deal"}, "Month", "Value")
in
    #"Unpivoted Other Columns"

结果
enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.