2015-04-04 93 views
1

我想在Excel中进行1000次模拟,然后总结每次试验的成功次数。我想改变试运行的尺寸。根据数组中的值求和

例如,我在Excel中的列中有1000个数字,范围从0 - 31。可以说前三个数字是28,3127。对于第一次运行,我想运行一个随机数生成器28次,然后总结多少个值小于.277。下一列将有31个试验,而下一个将有27个,依此类推,直到所有1,000个号码都被使用为止。

这是我到目前为止有:

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但我希望它随每次运行基于不同列中的值而更改。

回答

0

你很近!如果我对此有所了解,那么您想要进行1000次系列测试。每个系列可以是相同测试的0-31个循环,并且您将这些循环计数存储在一列中。看起来你所要做的就是使用另一个工作表将所有随机数存储在一列中,其余结果存储在其中。这是很多专栏!

除非您确实需要长期存储所有这些1和0,否则您可以使用另一个变量来执行计数并跳过将值写入单元格,直到得到结果为止。声明解决了真实。

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

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 

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

+0

这工作得很好! – 2015-04-04 04:40:46

+0

很高兴帮助。你有一个好的开始,只是错过了最后两块。祝你好运! – 2015-04-04 13:44:04