我已经看到很多关于合并的问题,但是我无法操纵(在我的入门级能力中)回答这个特定的问题,并将永远感激你的专业知识和帮助!!!
我希望将不同的单元格组合并为特定范围的相同值。
以下是输入和所需结果的示例。我将文件格式化为“0”和“否”不显示,但实际描述(用50%折扣代替)很长,无法在单个单元格中查看,因此需要合并单元格以更好地显示信息。还有多个商店每周都会添加新商店,因此我希望避免手动合并单元格。
输入
Month January February March April May
Store 1 Campaign Period no yes yes yes no
Campaign Details 0 50% off 50% off 50% off 0
Store 2 Campaign Period no no no yes yes
Campaign Details 0 0 0 spring fling spring fling
期望输出
Month January February March April May
Store 1 Campaign Period no yes yes yes no
Campaign Details 0 50% off 0
Store 2 Campaign Period no no no yes yes
Campaign Details 0 0 0 spring fling
答案 0 :(得分:1)
这应该让你开始。假设数据在“Sheet1”中。它将合并在“A”列中标有“Campaign Details”的行中的单元格。在具有相同值的相邻行单元上执行合并 - 将合并具有相同值的至少两个相邻单元。
Option Explicit
Sub MergeSameDetails()
Dim sht As Worksheet
Set sht = Worksheets("Sheet1")
Application.DisplayAlerts = False
With sht
Dim lastrow As Integer, i As Integer, j As Integer, cnt As Integer
Dim val As Variant
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = 1 To lastrow
If .Cells(i, "A").Value = "Campaign Details" Then
cnt = 1
val = .Cells(i, 2).Value
For j = 3 To 7
If val = .Cells(i, j).Value Then
cnt = cnt + 1
Else
If cnt >= 2 And val <> "0" Then
.Range(Cells(i, j - cnt), Cells(i, j - 1)).Merge
.Cells(i, j - cnt).HorizontalAlignment = xlCenter
End If
cnt = 1
val = .Cells(i, j).Value
End If
Next
End If
Next
End With
Application.DisplayAlerts = True
End Sub