首页 > 解决方案 > 如果其中一个单元格在 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 四、五、七 葡萄, 浆果, 浆果

标签: excelvbaconcatenation

解决方案


您可以使用 Power Query(在 Excel 2010+ 中提供)轻松完成此操作

  • 将光标放在数据表中,Data => Get&Transfrom => From Table/Range
  • 当 PQ 编辑器打开时,Home => Advanced Editor
    • 注意第2 行的表名
    • 用下面的代码替换M 代码
    • 将第 2 行的表名更改为您的实际表名
  • 代码Groups By列,然后执行自定义操作以在和A中创建分组项目的唯一列表;并将它们连接起来。BC

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"

在此处输入图像描述


推荐阅读