您可以使用Power Query 获得所需的输出,在 Windows Excel 2010+ 和 Office 365 Excel 中可用
- 选择原始表格中的某个单元格
Data => Get&Transform => From Table/Range
- 当 PQ UI 打开时,导航到
Home => Advanced Editor
- 记下代码第 2 行中的表名(以及标记为
Source2 的行的更下方)
- 用下面的M-Code替换现有代码
- 将粘贴代码的
Source 和Source2 行中的表名更改为您的“真实”表名
- 检查所有 cmets 以及
Applied Steps 窗口,以更好地了解算法和步骤
基本算法
M 码
let
//change Table name in next line to actual name in your workbook
Source = Excel.CurrentWorkbook(){[Name="sampleData"]}[Content],
//Read in the vacant name list
//Again, change Table name in next line to actual name in your workbook
Source2 = Excel.CurrentWorkbook(){[Name="vacantNames"]}[Content],
//Group by ID
#"Grouped Rows" = Table.Group(Source, {"ID"}, {
{"All", each _, type table [#"Order#"=number, PersonName=text, ID=text]}
}),
#"Removed Columns" = Table.RemoveColumns(#"Grouped Rows",{"ID"}),
//Group each ID by Order#
#"Added Custom" = Table.AddColumn(#"Removed Columns", "Custom", each Table.Group([All],"Order#",{"All2", each _})),
#"Removed Columns1" = Table.RemoveColumns(#"Added Custom",{"All"}),
//add index column to each subTable
#"Added Custom1" = Table.AddColumn(#"Removed Columns1", "Custom.1", each Table.AddIndexColumn([Custom],"IDX",0,1,Int64.Type)),
#"Removed Columns2" = Table.RemoveColumns(#"Added Custom1",{"Custom"}),
//expand tables
//we will replace names that do not have IDX=0
#"Expanded Custom.1" = Table.ExpandTableColumn(#"Removed Columns2", "Custom.1",
{"Order#", "All2", "IDX"}, {"Order#", "All2", "IDX"}),
//create index into vacant table
vacIDX = List.Generate(()=>[vIDX=0, i=0],
each [i] < Table.RowCount(#"Expanded Custom.1"),
each [vIDX = if Table.Column(#"Expanded Custom.1","IDX"){[i]}=0 then [vIDX] else [vIDX]+1, i = [i]+1],
each [vIDX]),
//Add index column to sample table
#"Added Index1" = Table.AddIndexColumn(#"Expanded Custom.1", "Index", 0, 1, Int64.Type),
//add Personal Names and ID
//The Index column gives us the position in the vacIDX list that corresponds to the "next" entry for substitution
// into the sample table
#"Added Custom2" = Table.AddColumn(#"Added Index1", "PersonName",
each if [IDX] = 0 then [All2][PersonName]{0}
else Source2[PersonName]{vacIDX{[Index]}}, Text.Type),
#"Added Custom3" = Table.AddColumn(#"Added Custom2", "ID",
each if [IDX] = 0 then [All2][ID]{0}
else Source2[ID]{vacIDX{[Index]}}, Text.Type),
//Remove unneeded columns and expand the table
#"Removed Columns3" = Table.RemoveColumns(#"Added Custom3",{"Order#", "IDX", "Index"}),
#"Expanded All2" = Table.ExpandTableColumn(#"Removed Columns3", "All2", {"Order#"}, {"Order#"})
in
#"Expanded All2"
结果