【问题标题】:Can't cumulate the sum of array elements with VBA无法用 VBA 累积数组元素的总和
【发布时间】:2013-04-15 22:26:53
【问题描述】:

我正在尝试在 4 值维度 (4,1) 的 excel 列中累积值的总和。

所以,我构建了下面的代码。对于 Result 侧列中的第一行,它应该与原始数组中的值相同。 但是,一旦它大于第一行,它应该获取结果的前一个元素(i-1)并将当前列元素(i)添加到它。

VBA 告诉我下标超出范围:/ 我不知道为什么......所以我什至不知道我的代码是否符合我的要求。

Sub CumulativeSum()
    Dim i As Integer
    Dim j As Integer
    Dim rColumn() As Variant
    Dim result() As Variant
    ReDim result(1 To 4)
    rColumn = Worksheets("Sheet1").Range("E1:E4").Value2

    For i = 1 To 4
        result(1) = rColumn(1, 1)
        For j = 2 To 3
            result(j) = rColumn(j, 1) + result(j - 1)
        Next j
   Next i
   Dim dest As Range
   Set dest = Worksheets("Sheet1").Range("F1")
   dest.Resize(4, 1).Value = result
End Sub

【问题讨论】:

  • 此代码无法编译。你遗漏了一些东西。
  • 所有数组都从索引 0 开始,除非使用 Option Base 1 或在数组 Dim vArray(1 To 5) 的声明中指定。您还需要初始化数组,因为它们目前没有元素。你也错过了“结束如果”
  • 我有一个新代码,我添加了 Option Base 1..

标签: arrays vba sum


【解决方案1】:
Sub CumulativeSum()

    Dim dest As Range
    Dim i As Integer
    Dim j As Integer
    Dim rColumn() As Variant
    Dim result() As Variant
    ReDim result(1 To 4)
    rColumn = Worksheets("Sheet1").Range("E1:E4").Value2

    result(1) = rColumn(1, 1)
    For j = 2 To 4
        result(j) = rColumn(j, 1) + result(j - 1)
    Next j

    Set dest = Worksheets("Sheet1").Range("F1")
    dest.Resize(4, 1).Value = Application.Transpose(result)

End Sub

【讨论】:

  • 有一个问题...如果我决定我想通过使用 Range(Cells(5,1), Cells(5,4)).Value 从范围中获取值,那会工作?因为我在一个文件上尝试过它并返回类型不匹配......:S
【解决方案2】:

没有足够的代表来添加评论,但是..您收到错误的原因是因为 Cells 的语法是 Cells([Row],[Column])。您将其输入为 Cells([Column],[Row])。

改用 Range(Cells(1, 5), Cells(4, 5))。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    相关资源
    最近更新 更多