累积出现“ true”或“ 1”的结果在单独的列中

时间:2018-10-09 03:19:19

标签: vba loops accumulate

我大约有100行,其中一列和另一列中均包含一个随机数生成器,其中基于该随机数和其他因素,计算值= A。我用if语句设置了一个列,以检查A是否在上限和下限之内,如果为true,则返回“ 1”(如果命中,则为命中),否则为“ 0”。我想运行一个循环并计算这些单元中随着时间推移的点击数。本质上,我需要一个累积结果的列,以便最终我可以看到哪个范围的点击次数最高,等等。

1 个答案:

答案 0 :(得分:0)

为简化起见,让我们先说一下,在开始之前,数据存储在工作表“ ws”上:

     A              | B                | C
1    Random Numbers | Calculated Value | Accumulated Value
2    0              | 1                | 
3    5              | 0                | 
4    8              | 1                | 
5    73             | 0                | 
6    2              | 0                | 

[...]

假设我们要运行10,000次,以查看哪些行获得了最高的累积值,表示为每个先前迭代的计算值之和。我建议使用以下VBA解决方案:

Sub AccumulateValues
    Dim MaxIterations As Long: MaxIterations = 10000        
    Dim curRow as Long, LastRow as Long, it as Long

    Application.Calculation = xlCalculationManual 'Required to set it to manual

    With ws
        LastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For it = 1 to MaxIterations

            'Force the Recalculation of Cells in columns A and B:
            Application.Calculate

            For curRow = 2 To LastRow                    
                'Sum the result of this iteration with the accumulated value 
                'until the previous iteration and stores it.
                ws.Cells(curRow, 3) = ws.Cells(curRow, 3) + ws.Cells(curRow, 2)    

            Next curRow
        Next it

    End With

End Sub