如果行中的两列(时间段和类型)与通过用户表单输入的用户匹配,我试图对每一行的最后一个单元格求和。我本来打算将For Each
循环与源和目标一起使用,但是我认为您不能有多个目标。对于目标,我声明了存储用户输入的字符串变量(Period
和Type
)。到目前为止,我有以下代码,但是在求和最后一个单元格以及求和最后一个单元格之前,无法弄清楚如何合并第二列以进行匹配。
Dim c As Range
Dim j As Integer
Dim Source As Worksheet
Dim Target As Worksheet
Set Source = ActiveWorkbook.Worksheets("Database")
Set Target = ActiveWorkbook.Worksheets(Period)
j = 2
For Each c In Source.Range("E2:E100000")
If c = Period Then 'And Type
'Sum code
j = j + 1
End If
Next c
答案 0 :(得分:0)
首先,听起来像一个简单的公式就可以解决的问题。
使用Period
和Type
的实际值,并假设F和Z列分别是Type列和最后一列(总和),公式将如下所示:
=SumIFS("Z2:Z100000","E2:E100000",Period,"F2:F100000",Type)
让我们现在谈论您的代码...
.Worksheets("Period")
j
在做什么?如果您想知道该行,请放下For Each
并使用For j = 2 to 100000
进行所有操作。然后像这样引用单元格: If Source.Cells(j,5) = Period And Source.Cells(j,6) = Type Then Sum = Sum + Source.Cells(j,26)
Offset
来切换列,例如:
And C.Offset(0,1) = Type Then Sum = Sum + C.Offset(0,21)
LastRow = Source.Range("E" & Source.Rows.Count).End(xlUp).Row
将其放在一起,看起来像这样:
Dim Source As Worksheet
Dim Row As Long, LastRow as Long
Dim Sum As Double
Set Source = ActiveWorkbook.Worksheets("Database")
With Source
LastRow = .Range("E" & .Rows.Count).End(xlUp).Row
For Row = 2 to LastRow
If .Cells(Row,5) = Period And .Cells(Row,6) = Type Then Sum = Sum + .Cells(Row,26)
Next
End With
或更快速的方法是将数据复制到变量(一次),并且在必须输出总和之前再也不必与工作表对话:
Dim Source As Worksheet
Dim vData 'As Variant
Dim Row As Long, LastRow as Long
Dim Sum As Double
Set Source = ActiveWorkbook.Worksheets("Database")
With Source
LastRow = .Range("E" & .Rows.Count).End(xlUp).Row
vData = .Range("A1:Z" & LastRow).Value2
' I started at Row 1 to make vData align better with the sheet
' and remove confusion with different offsets in the for loop.
End With
For Row = 2 to LastRow
If vData(Row,5) = Period And vData(Row,6) = Type Then Sum = Sum + vData(Row,26)
Next
希望我理解您的问题,并且我没有犯任何错误(因为我没有测试代码)。