本文介绍了如何在VBA中对可变范围的值求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张桌子,如下图所示。在列C中,如果列A具有相同的索引(列B),则需要求和。如果它们有相同的索引,我想把所有行的总和结果(如列D所示)。
不幸的是,具有相同索引的值的范围是可变的,我的宏只能使用2个索引求和。有人可以帮忙吗?谢谢!
子示例()
Dim ws As Worksheet
Dim LastRow As Long
Dim n,i As整数
设置ws = ActiveWorkbook.Sheets(Sheet2)
ws.Select
LastRow =表(Sheet2)。范围(A& ; Sheets(Sheet2)。Rows.Count).End(xlUp).Row
范围(C3:C& LastRow)。选择
Selection.ClearContents
对于i = 3 To LastRow
如果范围(B& i + 1) - 范围(B& i)= 0则
范围(C& ; i)= Range(A& i + 1)+ Range(A& i)
Else
范围(C& i)=范围(C& ; i - 1)
End If
Next i
End Sub
解决方案
这里有一种方法:
()
Dim ws As Worksheet
Dim LastRow As Long
设置ws = ActiveWorkbook.Sheets( Sheet2)
LastRow = ws.Range(A& ws.Rows.Count).End(xlUp).Row
带有ws.Range(C3:C& LastRow)
.ClearContents
.Value = ws。评估(INDEX(SUMIF(B3:B& LastRow&,B3:B& LastRow&,A3:A& LastRow&))))
End With
End Sub
I have a table as shown below.
In column C I would like to Sum values from column A if they have the same index (column B). I would like to put sum result for all the rows if they have same index (as shown in column D).
Unfortunately the range of values with same index is variable and my macro can sum values just with 2 indexes. Can anyone help with it, please? Thanks!
Sub example()
Dim ws As Worksheet
Dim LastRow As Long
Dim n, i As Integer
Set ws = ActiveWorkbook.Sheets("Sheet2")
ws.Select
LastRow = Sheets("Sheet2").Range("A" & Sheets("Sheet2").Rows.Count).End(xlUp).Row
Range("C3:C" & LastRow).Select
Selection.ClearContents
For i = 3 To LastRow
If Range("B" & i + 1) - Range("B" & i) = 0 Then
Range("C" & i) = Range("A" & i + 1) + Range("A" & i)
Else
Range("C" & i) = Range("C" & i - 1)
End If
Next i
End Sub
解决方案
Here's one way:
Sub example()
Dim ws As Worksheet
Dim LastRow As Long
Set ws = ActiveWorkbook.Sheets("Sheet2")
LastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
With ws.Range("C3:C" & LastRow)
.ClearContents
.Value = ws.Evaluate("INDEX(SUMIF(B3:B" & LastRow & ",B3:B" & LastRow & ",A3:A" & LastRow & "),)")
End With
End Sub
这篇关于如何在VBA中对可变范围的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!