【问题标题】:Combine two rows specific column if data is same?如果数据相同,则合并两行特定列?
【发布时间】:2018-05-21 18:14:56
【问题描述】:

我有如下输入

我需要如下输出

如果数据与公式相同,基本上如何仅合并A列相邻值?这是一张巨大的床单。我想应用公式,使任务自动化。

【问题讨论】:

  • 那么你尝试了什么?
  • 你在问什么?
  • @ScottCraner 更新了我的帖子。
  • 公式不会这样做,您需要 vba 代码。

标签: excel merge


【解决方案1】:
Sub G()

    Dim x&, start&, bottom&
    Application.DisplayAlerts = False

    '// Start from row two
    '// In your sample it's value "Text1"
    x = 2

    While Not IsEmpty(Cells(x, 1))

        '// "start" designates the start row with new text (see below)
        start = x

        '// As soon as we defined start row with new text, it's time to define the last row.
        '// Cells(x, 1) - is new text value
        '// SearchDirection:=xlPrevious means that search must be done from bottom of sought range
        '// This also means that no extra data must be under your data.
        '// So, this way we can get to know full range.
        '// For single distinct value the start and bottom will be the same row.
        bottom = Range("A:A").Find(Cells(x, 1), SearchDirection:=xlPrevious).Row

        '// Having start and bottom rows,
        '// we can get full range with new text by using Resize property.
        '// It sets new number of rows and columns having top-left cell as a start point.
        Cells(start, 1).Resize(bottom - start + 1).Merge

        '// The next cell after bottom cell is new value.
        x = bottom + 1

    Wend

    Application.DisplayAlerts = True

End Sub

【讨论】:

  • 您可能需要注意必须在 A 列上对数据进行排序,否则可能会合并错误数量的单元格,此代码将合并第一个实例和第一个实例之间的所有内容最后一个实例之间是否有任何其他文本。
  • @johnyL 谢谢。你能解释一下吗?我来自java背景。我在上面的代码中没有看到我们比较第 1 列数据的任何地方?
  • @ScottCraner 从 OP 的样本来看,A 列中的数据。 :) 我会指出“中间文本”。
  • @JohnyL 从未对数据的位置提出异议,只是 OP 在运行代码之前必须对 A 列进行排序以确保正确合并。否则很好地使用Find。我不会想到这一点,我会使用Application.Countif。你的会更快。
  • @ScottCraner 是的,我同意你的观点,Find 必须谨慎使用。需要确保不会出现任何间隙或额外数据。:)
猜你喜欢
  • 2017-03-07
  • 2012-09-12
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 2017-12-21
  • 1970-01-01
相关资源
最近更新 更多