excel - 如果其中一个单元格在 VBA 中相同,则需要在 excel 中合并行
问题描述
我有下表:
一个 | 乙 | C |
---|---|---|
一个 | 一 | 苹果 |
b | 二 | 橙 |
b | 三 | 香蕉 |
C | 四 | 葡萄 |
C | 五 | 浆果 |
一个 | 六 | 苹果 |
C | 七 | 浆果 |
我希望输出为:
一个 | 乙 | C |
---|---|---|
一个 | 一、六 | 苹果 |
b | 二三 | 橙子、香蕉 |
C | 四、五、七 | 葡萄,浆果 |
我在下面有这段代码:
Sub CombineRows()
Dim lngRow As Long
With ActiveSheet
Dim columnToMatch As Integer: columnToMatch = 1
Dim columnToConcatenate As Integer: columnToConcatenate = 2
Dim columnToConcatenate2 As Integer: columnToConcatenate2 = 3
lngRow = .Cells(65536, columnToMatch).End(xlUp).Row
.Cells(columnToMatch).CurrentRegion.Sort key1:=.Cells(columnToMatch), Header:=xlYes
Do
If .Cells(lngRow, columnToMatch) = .Cells(lngRow - 1, columnToMatch) Then
.Cells(lngRow - 1, columnToConcatenate) = .Cells(lngRow - 1, columnToConcatenate) & ", " & .Cells(lngRow, columnToConcatenate)
.Cells(lngRow - 1, columnToConcatenate2) = .Cells(lngRow - 1, columnToConcatenate2) & ", " & .Cells(lngRow, columnToConcatenate2)
.Rows(lngRow).Delete
End If
lngRow = lngRow - 1
Loop Until lngRow = 1
End With
我得到这个结果:
一个 | 乙 | C |
---|---|---|
一个 | 一、六 | 苹果,苹果 |
b | 二三 | 橙子、香蕉 |
C | 四、五、七 | 葡萄, 浆果, 浆果 |
解决方案
您可以使用 Power Query(在 Excel 2010+ 中提供)轻松完成此操作
- 将光标放在数据表中,
Data => Get&Transfrom => From Table/Range
- 当 PQ 编辑器打开时,
Home => Advanced Editor
- 注意第2 行的表名
- 用下面的代码替换M 代码
- 将第 2 行的表名更改为您的实际表名
- 代码Groups By列,然后执行自定义操作以在和
A
中创建分组项目的唯一列表;并将它们连接起来。B
C
M代码
注意:从最初的帖子简化的代码
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"A", type text}, {"B", type text}, {"C", type text}}),
#"Grouped Rows" = Table.Group(#"Changed Type", {"A"}, {
{"B", each Text.Combine(List.Distinct(_[B]),", "), type text},
{"C", each Text.Combine(List.Distinct(_[C]),", "), type text}
})
in
#"Grouped Rows"
推荐阅读
- python - 在 python 中读取文件并仅打印文件名
- java - 如何在Junit中写描述?
- python-3.x - 计算最终金额的折扣
- php - 通过 YouTube 数据 API 上传的视频将变为私有视频
- jmeter - Jmeter 是否支持将 Jmx 文件直接导入 azure devops
- node.js - 如何使用 OAEP 使用此公钥加密数据
- azure - Azure Pipelines YAML 源
- javascript - 提交时未清空 SimpleMDE 组件
- r - R data.table:如何合并 data.tables 列表?
- json - 如何将模型 json 绑定到控制器中的组合框?