每次执行一个函数时运行计数器(VBA)

我正在为我的数组索引而挣扎。 我希望数组的上限是Function 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 

你可以使用一个静态variables来实现这一点。 函数调用之间存在一个静态variables的值。 请参阅下面的解决scheme。 在下面的代码中运行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 

使您的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