如何使用 VBA 在 Excel 中求和/合并相似的行?
我正在尝试在 Excel 的 VBA 中构建一个简单的宏,它将对具有相同名称(第一列中的值)的所有行进行求和。 那么例如
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 圣经。
I'm trying to build a simple macro in VBA for Excel that would SUM [merge] all the rows that have the same name (value in the first columns).
So for example
ExampleRowA 1 0 1 1 3 4
ExampleRowA 2 1 2 2 1 0
ExampleRowC 9 7 7 7 2 5
the result should look like this
ExampleRowA 3 1 3 3 4 4
ExampleRowC 9 7 7 7 2 5
We can assume that the rows that need to be merged are not scattered, and can only appear one after another.
I did something like this, and it almost works, except I have to run it two times.
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
I've done some programming in other scripting languages but am new to VB/VBA and don't know the possibilites/limitations of it.
In other languages I would probably use arrays but I don't get the way they work here. I can't deny that because of time constraints I prefer to learn by analyzing examples rather than reading a 500+ page VBA Bible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试这样的事情:
Try somthing like this:
这段代码更容易阅读并且可以完成工作:
This code is easier to read and does the job:
'如果你必须运行宏两次,idk 放一个
<代码>
1:
在你的宏的顶部和底部放
转到1
'这将为你运行两次
'或者您可以在不同的宏中调用它两次。由你决定
'if you have to run the macro twice, idk put a
1:
on top of your macro and on the bottom put
goto 1
'that will run it twice for you
'or you can call it twice in a different macro. up to you
对于您的问题,您不需要宏或任何 VBA 代码。
您可以首先打开包含重复值的表的工作表。
操作步骤:
For your Problem, you don't need the Macros or any VBA code.
You can start by opening the sheet with Table containing duplicate values.
Follow Steps: