基于数组中的值的总和

时间:2015-04-04 02:26:30

标签: excel vba excel-vba sum

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

例如,我在Excel的一列中有1,000个数字,范围从0 - 31。可以说前三个数字是283127。对于第一次运行,我想运行一个随机数生成器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。如果它是设定数字ij = 1 to 34,但我希望它根据不同列中的值随每次运行而变化。

1 个答案:

答案 0 :(得分: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

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