如何使用VBA在Excel中合并/合并相似的行?
我正在尝试在VBA for Excel中构build一个简单的macros,将SUM [合并]具有相同名称(第一列中的值)的所有行。 所以例如
ExampleRowA 1 0 1 1 3 4 ExampleRowA 2 1 2 2 1 0 ExampleRowC 9 7 7 7 2 5
结果应该是这样的
ExampleRowA 3 1 3 3 4 4 ExampleRowC 9 7 7 7 2 5
我们可以假定需要合并的行不是分散的,只能一个接一个地出现。
我做了这样的事,几乎可以工作,除了我必须运行两次。
LastRow = ActiveSheet.UsedRange.Rows.Count Set r = ActiveSheet.UsedRange.Resize(1) With Application.WorksheetFunction For iRow = 2 To LastRow If Cells(iRow, 1) = Cells(iRow + 1, 1) Then LastCol = r(r.Count).Column SumCol = LastCol + 1 For iCol = 2 To SumCol Cells(iRow, iCol) = .Sum(Range(Cells(iRow, iCol), Cells(iRow + 1, iCol))) Next iCol Rows(iRow + 1).Delete End If Next iRow End With
我已经用其他脚本语言编写了一些程序,但对VB / VBA来说是新的,不知道它的可能性和局限性。
在其他语言中,我可能会使用数组,但我不明白他们在这里工作的方式。 我不能否认,由于时间的限制,我宁愿通过分析实例来学习,而不是阅读500页以上的VBA圣经。
尝试像这样的东西:
LastRow = ActiveSheet.UsedRange.Rows.Count Set r = ActiveSheet.UsedRange.Resize(1) With Application.WorksheetFunction For iRow = LastRow-1 to 2 step -1 do while Cells(iRow, 1) = Cells(iRow + 1, 1) LastCol = r(r.Count).Column SumCol = LastCol + 1 For iCol = 2 To SumCol Cells(iRow, iCol) = .Sum(Range(Cells(iRow, iCol), Cells(iRow + 1, iCol))) Next iCol Rows(iRow + 1).Delete loop Next iRow End With
这段代码更容易阅读和完成工作:
Sub Macro1() Dim ColumnsCount As Integer ColumnsCount = ActiveSheet.UsedRange.Columns.Count ActiveSheet.UsedRange.Activate Do While ActiveCell.Row <= ActiveSheet.UsedRange.Rows.Count If ActiveCell.Value = ActiveCell.Offset(1, 0).Value Then For i = 1 To ColumnsCount - 1 ActiveCell.Offset(0, i).Value = ActiveCell.Offset(0, i).Value + ActiveCell.Offset(1, i).Value Next ActiveCell.Offset(1, 0).EntireRow.Delete shift:=xlShiftUp Else ActiveCell.Offset(1, 0).Select End If Loop End Sub
'如果你必须两次运行这个macros,idk会1: on top of your macro and on the bottom put goto 1
放置一个1: on top of your macro and on the bottom put goto 1
,它会为你运行两次,或者你可以在不同的macros中调用它两次。 由你决定
对于你的问题,你不需要macros或任何VBA代码。
您可以通过打开包含重复值的表格开始。 遵循步骤:
- 放置Excel光标,在那里你想要合并的数据。然后,转到数据选项卡>合并。
- 合并对话框将出现。
- 这里input具有重复值的表格,点击添加以添加这些值。
- 然后,select行/列,无论哪个值重复。 在这个左列。
- 只需点击确定,你就完成了。