Excel VBA运行求和函数

093gszye  于 2023-08-08  发布在  其他
关注(0)|答案(2)|浏览(114)

我有一个UDF,它试图将一列数字的运行和制成表格。如果列A是我的数据,列B是UDF输出,它看起来像这样:

Column A | Column B
5        | 5
10       | 15
1000     | 1015

字符串
诸如此类。
下面是我的代码:

Option Explicit
Public Function runningSum(myCell As range) As Integer

Dim rowNum As Integer
Dim colNum As Integer
Dim tempSum As Integer
Dim i As Integer
Dim ws As Worksheet

rowNum = myCell.row
colNum = myCell.Column
tempSum = 0
Set ws = ActiveSheet

With ws
    For i = 1 To rowNum
        tempSum = tempSum + ws.Cells(i, colNum).Value
    Next i
    runningSum = tempSum
End With
Exit Function

End Function


我遇到的问题是:在第39次和每次连续迭代时,我得到一个#VALUE错误。帮帮忙好吗谢啦,谢啦

ybzsozfc

ybzsozfc1#

似乎您的数字变得太大,integer无法容纳。尝试将数据类型切换为long

q3qa4bjr

q3qa4bjr2#

下面的代码是有用的,工作完美模型:1选项显式公共函数RunningSum(rng As Range)As Integer Dim Cell As Range Dim Counter As Long Dim tempSum As Integer
Counter = WorksheetFunction.Count(rng)+ 1 tempSum = 0
对于每个单元格,计数器=计数器-1
tempSum = tempSum +(单元格值 * 计数器)
下一单元格
RunningSum =临时和
结束函数
型号:2
Option显式公共函数RunSumT(rng As Range)As Integer Dim Cell As Range
Dim tempSum As Integer Dim tempSum1 As Integer
tempSum = 0 tempSum1 = 0

For Each Cell In rng

tempSum = tempSum + (Cell.Value)
    tempSum1 = tempSum1 + tempSum + (Cell.Value)

字符串
下一单元格
RunSumT = tempSum1 - tempSum
结束函数

相关问题