我对我的数组索引略有困难。我希望数组的上限是函数RandomizeDice执行的时间量。任何帮助是极大的赞赏。
Function RandomizeDice()
RandomizeDice = Application.WorksheetFunction.RandBetween(1, 6)
End Function
Sub RollDice()
Dim DiceOne() As Variant
Dim DiceTwo() As Variant
Dim SumDice() As Variant
Dim i As Integer
ReDim DiceOne(i) As Variant
ReDim DiceTwo(i) As Variant
ReDim SumDice(i) As Variant
Call arraySet(DiceOne(), DiceTwo(), SumDice())
Debug.Print SumDice(i)
'Debug.Print SumDice(0)
' Debug.Print ("Dice: " & DiceOne(0) & " " & DiceTwo(0))
' Debug.Print ("Sum: " & DiceOne(0) + DiceTwo(0))
End Sub
Sub arraySet(ByRef a() As Variant, b() As Variant, c() As Variant)
'Dim DiceOne() As Integer
'Dim DiceTwo() As Integer
Dim i, j As Integer
'Dim intSumDice() As Integer
For i = 0 To j = i + 1
a(i) = RandomizeDice() 'dice1
b(i) = RandomizeDice() 'dice2
c(i) = a(i) + b(i) 'sum
Next i
Debug.Print i
Debug.Print ("Dice: " & a(0) & " " & b(0))
Debug.Print ("Sum: " & a(0) + b(0))
End Sub
答案 0 :(得分:1)
使你的RollDice
使用卷数作为参数
Sub RollDice(ByVal nRolls As Long)
ReDim DiceOne(1 To nRolls) As Long, DiceTwo(1 To nRolls) As Long, SumDice(1 To nRolls) As Long
For nRolls = 1 To nRolls
DiceOne(nRolls) = RandomizeDice()
DiceTwo(nRolls) = RandomizeDice()
SumDice(nRolls) = DiceOne(nRolls) + DiceTwo(nRolls)
Next
' Now do what you want with these arrays
End Sub
Sub testing()
RollDice 100
End Sub
答案 1 :(得分:0)
您可以使用静态变量来实现此目的。函数调用之间的静态变量值仍然存在。请参阅下面的解决方案。在下面的代码中运行Sub Main
几次,看它是否有效。
Option Explicit
Public Type structPairOfDice
diceOne As Integer
diceTwo As Integer
rollNum As Integer
End Type
Function RandomizeDice() As Integer
RandomizeDice = Application.WorksheetFunction.RandBetween(1, 6)
End Function
Function RollDice(structDice As structPairOfDice) As structPairOfDice
Static iRollNum As Integer
iRollNum = iRollNum + 1
With structDice
.rollNum = iRollNum
.diceOne = RandomizeDice()
.diceTwo = RandomizeDice()
End With
RollDice = structDice
End Function
Sub PrintResults(structDice As structPairOfDice)
With structDice
Debug.Print "Roll #: " & .rollNum
Debug.Print "Dice: " & .diceOne & ", " & .diceTwo
Debug.Print "Sum: " & .diceOne + .diceTwo
Debug.Print
End With
End Sub
Sub Main()
Dim structDice As structPairOfDice
PrintResults RollDice(structDice)
End Sub