按场景/年重复对列中的46个单元格求和

时间:2015-09-30 21:21:13

标签: excel sum aggregate subtotal

对于各种增长情景,我有以下区域经济数据,其中包含截至2100年的各部门估计产出。

我想总结每个部门的价值,以获得区域产出估算。这需要每46个单元重复聚合输出列,将结果放在另一列中(最好还附加其他信息,例如年份/方案ID等)。

因为有> 1,000,000个单元格,所以这不是一项可以手工完成的工作。按情景,年份和地区划分所有部门的区域产出的最简单方法是什么?

以下是一些示例数据:

scenario  year   region_id region_name  sector_id sector_name   value/output
1A_1C_1C    2000    1   London  2   Mining & quarrying      642.2357178
1A_1C_1C    2000    1   London  3   Food, drink & tobacco   1979.741211
1A_1C_1C    2000    1   London  4   Textiles etc            586.706604
1A_1C_1C    2000    1   London  5   Wood & paper            318.1535339
1A_1C_1C    2000    1   London  6   Printing & recording    1749.062012
...             
1A_1C_1C    2000    2   South East  1   Agriculture etc     771.9697876
1A_1C_1C    2000    2   South East  2   Mining & quarrying  542.2153931
1A_1C_1C    2000    2   South East  3   Food, drink & tob.  1990.234009
1A_1C_1C    2000    2   South East  4   Textiles etc        205.3581085

编辑:可以通过获取第7列中每个区域的输出总和并将它们放在第8列来报告结果。理想情况下,第9列将包含特定区域名称,第10列将包括特定方案变体,像这样:

 Output        Region        Scenario       Year
 XXXXXX        London        1A_1C_1C       2000
 XXXXXX        South East    1A_1C_1C       2000
 ...
 XXXXXX        London        1B_1C_1A       2000
 XXXXXX        South East    1B_1C_1A       2000
 ...

编辑:将“年份”添加到输出示例

2 个答案:

答案 0 :(得分:0)

看起来你实际上是在要求聚合的SQL SELECT语句,也许它应该被视为这样。

Sub Sheets_Group_Having()
    'Dim cnx As ADODB.Connection, rs As ADODB.Recordset
    Dim cnx As Object, rs As Object
    Dim sWS As String, sWB As String, sCNX As String, sSQL As String
    Dim ws1TBLaddr As String

    sWB = ThisWorkbook.FullName
    sWS = "Source Data Worksheet Name HERE"   `<~~ set the worksheet with the source data
    ws1TBLaddr = WorkSheets(sWS).Cells(1, 1).CurrentRegion.Address(0, 0)
    sCNX = "Provider=Microsoft.Jet.OLEDB.12.0;Data Source=" & sWB _
        & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"

    Set cnx = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")

    cnx.Open sCNX

    sSQL = "SELECT SUM(w1.[value/output]), w1.[region_name], w1.[scenario], w1.[year] FROM [" & sWS & "$" & ws1TBLaddr & "] w1"
    sSQL = sSQL & " GROUP BY w1.[region_id], w1.[region_name], w1.[scenario], w1.[year]"
    sSQL = sSQL & " ORDER BY w1.[region_id], w1.[scenario]"
    'Debug.Print sSQL

    rs.Open sSQL, cnx

    With Worksheets.Add(after:=Sheets(Sheets.Count))
        .Name = "Summary Data"
        .Range("A1").Resize(1, 4) = Array("output", "region", "scenario", "year")
        .Range("A2").CopyFromRecordset rs
    End With

    rs.Close: Set rs = Nothing
    cnx.Close: Set cnx = Nothing
End Sub

答案 1 :(得分:0)

我研究了如何在Excel中进行数值计算。这是公式:

 =SUM(OFFSET($E$2,(ROW()-2)*46,0,46,1))

使用OFFSET函数,每隔46行向下汇总E2中的所有值。诀窍在于row(),它返回行号,从这个数字取2(​​我在C2上开始),然后将它乘以46,将SUM函数向下移动。