具有多个表格的Excel中的条件求和

时间:2015-03-27 12:12:48

标签: excel vba excel-vba excel-2010

我的数据看起来像这样,它有3列:城镇代码,病区代码和该病房的相应人口:

| Town  |  Ward | Population |
|  1000 | 10001 |     20     |
|  1000 | 10002 |     30     |
|  1000 | 10003 |     40     |
|  1234 | 12341 |     50     |
|  1234 | 12342 |     35     |

我无法在vba中编写代码,该代码将为我提供城镇下所有病房的人口总和(即城镇总人口)。
注意事项: - 我有一个巨大的数据集。
我有多张床单,我有相同类型的数据,有不同的城镇ID(每个城镇的病房数也不同)。如果您能在繁忙的日程安排中抽出一些时间,请提供帮助。

1 个答案:

答案 0 :(得分:0)

这是您的解决方案

How to perform SumIf using VBA on an array in Excel

 Sub FasterThanSumifs()
    'FasterThanSumifs Concatenates the criteria values from columns A and B -
    'then uses simple IF formulas (plus 1 sort) to get the same result as a sumifs formula

    'Columns A & B contain the criteria ranges, column C is the range to sum
    'NOTE: The data is already sorted on columns A AND B

    'Concatenate the 2 values as 1 - can be used to concatenate any number of values
    With Range("D2:D25001")
        .FormulaR1C1 = "=RC[-3]&RC[-2]"
        .Value = .Value
    End With

    'If formula sums the range-to-sum where the values are the same
    With Range("E2:E25001")
        .FormulaR1C1 = "=IF(RC[-1]=R[-1]C[-1],RC[-2]+R[-1]C,RC[-2])"
        .Value = .Value
    End With

    'Sort the range of returned values to place the largest values above the lower ones
    Range("A1:E25001").Sort Key1:=Range("D1"), Order1:=xlAscending, _
    Key2:=Range("E1"), Order2:=xlDescending, Header:=xlYes
    Sheet1.Sort.SortFields.Clear

    'If formula returns the maximum value for each concatenated value match &
    'is therefore the equivalent of using a Sumifs formula
    With Range("F2:F25001")
        .FormulaR1C1 = "=IF(RC[-2]=R[-1]C[-2],R[-1]C,RC[-1])"
        .Value = .Value
    End With

    End Sub