【发布时间】:2019-08-17 20:58:30
【问题描述】:
我有一个示例 MS Excel 表格:
我正在尝试编写一个允许我比较行的 VBA 宏,比较是使用多个单元格 (A2:E2) 完成的,其余单元格 (F2:I2) 将合并其值而不进行比较。我希望能够比较一行 - 单元格(A2:E2)到单元格(A3:E3),然后单元格(A2:E2)到单元格(A4:E4)......完成比较后它会合并重复项 - 这样单元格(Fx:Ix)也会合并。
最终效果如下:
到目前为止,我已经想出了这段代码,但运行它会使 Excel 崩溃。任何形式的建议将不胜感激。
提前致谢
Sub MergeDuplicateRows()
Dim i As Long
Dim j As Long
Dim RowCount As Long
Dim sameRows As Boolean
sameRows = True
RowCount = Rows.Count
Application.DisplayAlerts = False
Application.ScreenUpdating = False
For i = 1 To Range("B" & RowCount).End(xlUp).Row
For j = 1 To 5
If StrComp(Cells(i, j), Cells(i + 1, j), vbTextCompare) Then
sameRows = False
End If
Next j
If sameRows Then
Range(Cells(i, 1), Cells(i + 1, 1)).Merge
Range(Cells(i, 2), Cells(i + 1, 2)).Merge
Range(Cells(i, 3), Cells(i + 1, 3)).Merge
Range(Cells(i, 4), Cells(i + 1, 4)).Merge
Range(Cells(i, 5), Cells(i + 1, 5)).Merge
Range(Cells(i, 6), Cells(i + 1, 6)).Merge
Range(Cells(i, 7), Cells(i + 1, 7)).Merge
Range(Cells(i, 8), Cells(i + 1, 8)).Merge
Range(Cells(i, 9), Cells(i + 1, 9)).Merge
End If
sameRows = True
Next i
Application.DisplayAlerts = True
End Sub
【问题讨论】:
-
在你的最终结果中,为什么
var8在foo1的行中有一个x(没有M)? -
"...但运行它会导致 Excel 崩溃" - 这是什么意思?您收到的是实际的错误消息,还是 Excel 只是冻结?
-
excel 只是冻结并且永远不会唤醒 - 出现一个对话框,要求重新启动 MS Excel...
-
最后一个问题 - 是否所有行都可能在彼此的顶部/下方匹配,或者它们可以在工作表上的任何位置?
-
你也永远不会恢复
ScreenUpdating。