我想将工作表中两个范围的内容与另一个工作表上的两个字符串进行比较。如果满足这两个条件,则它旁边的单元格必须与所有先前的匹配相加。
将其与一个标准进行比较可以正常运行的代码:
Sub Makro1()
Dim FB As String
FB = ActiveWorkbook.Sheets("Form").Range("B3").Value
Dim MyRangeA As Range
Dim A As Range
Dim MyTotal As Long
Dim LastRow As Long
MyTotal = 0
LastRow = ActiveWorkbook.Sheets("Downloads").Cells(Cells.Rows.Count, "F").End(xlUp).Row
Set MyRangeA = ActiveWorkbook.Sheets("Downloads").Range("F3:F" & LastRow)
For Each A In MyRangeA
If A.Value = FB Then
MyTotal = MyTotal + A.Offset(, 1).Value
End If
ActiveWorkbook.Sheets("Downloads").Range("K3") = MyTotal
Next
End Sub
但是,我无法弄清楚如何在我的范围内插入另一个标准。这是我目前的尝试不起作用:
Sub Macro1()
Dim FB As String
Dim MTH As String
FB = ActiveWorkbook.Sheets("Form").Range("B3").Value
MTH = ActiveWorkbook.Sheets("Form").Range("B5").Value
Dim MyRangeA As Range
Dim A As Range
Dim MyRangeB As Range
Dim B As Range
Dim MyTotal As Long
Dim LastRow As Long
MyTotal = 0
LastRow = ActiveWorkbook.Sheets("Downloads").Cells(Cells.Rows.Count, "F").End(xlUp).Row
Set MyRangeA = ActiveWorkbook.Sheets("Downloads").Range("F3:F" & LastRow)
Set MyRangeB = ActiveWorkbook.Sheets("Downloads").Range("D3:D" & LastRow)
For Each A In MyRangeA
For Each B In MyRangeB
If B.Value = MTH Then
MyTotal = MyTotal + A.Offset(, 1).Value
End If
Next
ActiveWorkbook.Sheets("Downloads").Range("L3") = MyTotal
Next
End Sub
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:0)
正如查尔斯威廉姆斯所写,你可以使用SUMIFS。如果您对不区分大小写的匹配感到满意,可以在VBA例程中使用它:
MyTotal = WorksheetFunction.SumIfs(MyRangeA.Offset(, 1), MyRangeA, FB, MyRangeB, MTH)
或者,如果这有问题,您可以循环测试每个项目。但是,根据数据的大小,通常可以更快地将所有内容读入VBA数组,并循环显示,而不是返回到每个项目的工作表。此外,通过索引进行迭代通常更快。对于I = 1到n ...接下来我而不是通过对于每个某些对象...下一个对象类型迭代。因此,如果您不想使用上述内容,我会尝试类似于以下的代码段:
Dim I As Long
Dim vData As Variant
vData = Union(MyRangeA, MyRangeA.Offset(, 1), MyRangeB)
For I = 1 To UBound(vData)
If vData(I, 1) = FB And vData(I, 3) = MTH Then
MyTotal = MyTotal + vData(I, 2)
End If
Next I
根据您的要求,您也可以考虑添加
Option Compare Text
到宏的顶部。