Sum变量通过固定第一列来调整VBA

时间:2017-03-03 15:27:37

标签: vba dynamic sum range

我想知道如何通过修复列来对范围求和,然后将值保存到数组中。

A  B  C  D  E  F  G
1  -  10 -  4  -  1
2  -  98 -  1  -  2
3  -  5  -  9  -  7
4  -  80 -  54 -  10

我想做的是:

  1. 对A列中的值求和 - >将总和放入sumArray()
  2. 将A列到C的值相加 - >将总和放入sumArray
  3. 将A列中的值相加到E - >将总和放入sumArray
  4. 将A列到G的值相加 - >将总和放入sumArray
  5. 基本上,列和行的维度是动态的。我的问题是我该怎么做?

    我希望我能正确解释自己

    先谢谢你们。

2 个答案:

答案 0 :(得分:0)

Sub summarize()
Dim i As Integer
Dim maxCol, maxRow As Integer
maxCol = 6
maxRow = 7
Dim ws As Worksheet
Set ws = ActiveWorkbook.ActiveSheet

Dim sumArray(100) As Integer
For i = 1 To maxCol
    maxRow = ws.Cells(Rows.Count, i).End(xlUp).Row
    sumArray(i) = CInt(Application.Sum(ws.Range(ws.Cells(1, 1), ws.Cells(maxRow, i))))
    Debug.Print sumArray(i)
Next i
End Sub

答案 1 :(得分:0)

你可以用这个:

Sub DoSumArray()
    Dim icol As Long

    With ActiveSheet.UsedRange
        ReDim SumArray(1 To .columns.Count / 2 + 1)
        For icol = 1 To .columns.Count Step 2
            SumArray(icol \ 2 + 1) = WorksheetFunction.SUM(.columns(icol))
        Next
    End With
End Sub