Excel - 将多列合并为一列

标签 excel vba

我的 Excel 工作表如下所示

      c1        c2      c3      c4

ROW1   abc      def      1       2

ROW2   abc      def      3       4

ROW3   klm      efg     11       5

ROW4   klm      efg     12      89

我想将数据合并到一列中,并用一个逗号分隔重复的 c1 条目。所以 Excel 工作表应该如下所示,

       c1        c2      c3      c4

ROW1   abc      def      1,3     2,4

ROW2   klm      efg     11,12    5,89

最佳答案

此代码将

  • 在当前工作表的 A:D 列上运行
  • 将 A 列和 B 列中常见的记录分别与 C 列和 D 列的组合值分组在一起
  • 运行时不区分大小写
  • 输出到新工作表

enter image description here

    Sub QuickCombine()
    Dim X()
    Dim Y()
    Dim objDic As Object
    Dim lngRow As Long
    Dim lngCol As Long
    Dim ws As Worksheet

    X = Range([a1], Cells(Rows.Count, "D").End(xlUp))
    Y = X
    Set objDic = CreateObject("scripting.dictionary")

    For lngRow = 1 To UBound(X, 1)
        If Not objDic.exists(LCase$(X(lngRow, 1) & X(lngRow, 2))) Then
            objDic.Add LCase$(X(lngRow, 1) & X(lngRow, 2)), lngRow
        Else
            Y(lngRow, 1) = vbNullString
            Y(objDic.Item(LCase$(X(lngRow, 1) & X(lngRow, 2))), 3) = Y(objDic.Item(LCase$(X(lngRow, 1) & X(lngRow, 2))), 3) & "," & X(lngRow, 3)
            Y(objDic.Item(LCase$(X(lngRow, 1) & X(lngRow, 2))), 4) = Y(objDic.Item(LCase$(X(lngRow, 1) & X(lngRow, 2))), 4) & "," & X(lngRow, 4)
        End If
    Next

    Set ws = Sheets.Add

    ws.[a1].Resize(UBound(X, 1), UBound(X, 2)) = Y
    ws.Columns("A").SpecialCells(xlBlanks).EntireRow.Delete

End Sub

关于Excel - 将多列合并为一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10612386/

相关文章:

excel - Excel 2019 是否有类似索引匹配或 vlookup 的功能来查找添加交叉表的行中的值?

vba - 如何在 Excel 中生成 GUID?

Excel 数据透视表小计

excel - 如何解决这个 "ambiguous name detected Worksheet_Change"?

VBA:如何比较两个不同工作表中的两列

java - Poi 中带有超链接的称重传感器故障?

excel - 在 R 中,如何找到最佳变量以最大化或最小化两个数据集之间的相关性

excel - F#,Office 中的另一个 VBA?

vba - 根据单元格中的值对单元格进行颜色

excel - 复制到一行中的最后一个非空单元格