基于数组中值的总和

我想在Excel中进行1000次模拟,然后总结每个试验的成功次数。 我想改变试运行的大小。

例如,我在Excel中有一个从031 1000个数字。 可以说前三个数字是2827 。 对于第一次运行,我想运行一个随机数生成器28次,然后总结有多less个值小于.277 。 下一栏将有31个审判,下一个将有27个,依此类推,直到全部使用1000个号码。

这是我迄今为止:

 Private Sub CommandButton1_Click() Dim i As Long Dim j As Long For i = 1 To 1001 For j = 1 To iCol.Value Range("A" & j) = Rnd() If Cells(j, 1).Value < 0.277 Then Cells(j, i) = 1 Else Cells(j, i) = 0 End If Next j Next i End Sub 

我遇到的问题是用For j = 1 To iCol.Value 。 如果是一组数字, i会做j = 1 to 34但是我希望它根据不同列中的值每次运行都会改变。

你近了! 如果我理解这一点,你想要运行一系列的testing1000次。 每个系列可以是相同testing的0-31个周期,并且您将这些周期数存储在列中。 看起来你所要做的就是使用另一个工作表将所有的随机数字存储在一个列中,其余的结果在其中。 这是很多专栏!

除非你真的需要长期存储所有这些1和0,你可以使用另一个variables来进行计数,并跳过将值写入单元格,直到得到结果…语句解决的次数为真。

你可以做这样的事情(你可能不得不改变参考或两个,因为我看不到你的工作簿)

 Private Sub CommandButton1_Click() Dim i As Long Dim j As Long 'Some new variables/objects Dim lCurrentCount As Long Dim iCol Dim ws As Worksheet 'Set this to the source sheet (where your trial counts are) Set ws = ActiveWorkbook.Sheets(2) 'This will be used to keep track of how many times the test 'was true without using the cells/columns to store data lCurrentCount = 0 For i = 1 To 1000 'This is what will incriment you to the next row to get a new trial count iCol = ws.Cells(i, 1) For j = 1 To iCol If Rnd() < 0.277 Then 'If it's true, add one to the current count 'If not go to the next lCurrentCount = lCurrentCount + 1 End If If j = iCol Then 'If this is the last one in a trial, put the 'True count next to the cycle number Range("B" & i) = lCurrentCount lCurrentCount = 0 End If Next j Next i End Sub 

但是,如果你真的需要保留所有这些单独的结果,它仍然是一个基本的想法。 您需要一个单元格或范围对象,您可以使用它来将源代码行与for循环一起增加。

 Private Sub CommandButton1_Click() Dim i As Long Dim j As Long 'Some new variables/objects Dim iCol As Long Dim wsSource As Worksheet Dim wsTarget As Worksheet 'Set this to the source sheet (where your trial counts are) Set wsSource = ActiveWorkbook.Sheets(2) 'Set this to the target sheet (where your trial Results will go) Set wsTarget = ActiveWorkbook.Sheets(1) For i = 1 To 100 'This is what will incriment you to the next row to get a new trial count 'Using i in the cells reference to what I assume is another sheet iCol = wsSource.Cells(i, 1) For j = 1 To iCol wsTarget.Range("A" & j) = Rnd() If wsTarget.Cells(j, 1).Value < 0.277 Then wsTarget.Cells(j, i) = 1 Else wsTarget.Cells(j, i) = 0 End If Next j Next i End Sub 

看起来像一些有趣的科学,希望它有帮助!