将随机骰子的值放入数组中(VBA)
Put the value of random dice into an array (VBA)
我想知道如何创建一个包含三个给定函数返回值的数组。我没有将数据放入 excel 的任何地方,所以我不能使用 "range"。我相信有一个解决方案,但我还没有弄清楚。
'randomize first dice
Function DiceOne(ByRef intDiceOne As Integer)
intDiceOne = Application.WorksheetFunction.RandBetween(1, 6)
DiceOne = intDiceOne
End Function
'randomize second dice
Function DiceTwo(ByRef intDiceTwo As Integer)
intDiceTwo = Application.WorksheetFunction.RandBetween(1, 6)
DiceTwo = intDiceTwo
End Function
'add first and second dice
Function RollDice()
Dim intDiceOne As Integer
Dim intDiceTwo As Integer
Dim intSumDice As Integer
Dim i As Integer
DiceOne intDiceOne
DiceTwo intDiceTwo
intSumDice = intDiceOne + intDiceTwo
RollDice = intSumDice
'Application.Range("dice_one") = intDiceOne
'Application.Range("dice_two") = intDiceTwo
'Application.Range("dice_sum") = intSumDice
'Debug.Print "The roll value is " & intSumDice
End Function
您不需要每个骰子都有单独的功能,也不需要 ByRef
。这样做:
Function RollD6()
RollD6 = Application.WorksheetFunction.RandBetween(1, 6)
End Function
Sub RollDice()
Dim Dice(2) As Integer
For i = 0 To 2
Dice(i) = RollD6()
Next
Debug.Print("Dice: " & Dice(0) & " " & Dice(1) & " " & Dice(2))
Debug.Print("Sum: " & Dice(0) + Dice(1) + Dice(2))
End Sub
我想知道如何创建一个包含三个给定函数返回值的数组。我没有将数据放入 excel 的任何地方,所以我不能使用 "range"。我相信有一个解决方案,但我还没有弄清楚。
'randomize first dice
Function DiceOne(ByRef intDiceOne As Integer)
intDiceOne = Application.WorksheetFunction.RandBetween(1, 6)
DiceOne = intDiceOne
End Function
'randomize second dice
Function DiceTwo(ByRef intDiceTwo As Integer)
intDiceTwo = Application.WorksheetFunction.RandBetween(1, 6)
DiceTwo = intDiceTwo
End Function
'add first and second dice
Function RollDice()
Dim intDiceOne As Integer
Dim intDiceTwo As Integer
Dim intSumDice As Integer
Dim i As Integer
DiceOne intDiceOne
DiceTwo intDiceTwo
intSumDice = intDiceOne + intDiceTwo
RollDice = intSumDice
'Application.Range("dice_one") = intDiceOne
'Application.Range("dice_two") = intDiceTwo
'Application.Range("dice_sum") = intSumDice
'Debug.Print "The roll value is " & intSumDice
End Function
您不需要每个骰子都有单独的功能,也不需要 ByRef
。这样做:
Function RollD6()
RollD6 = Application.WorksheetFunction.RandBetween(1, 6)
End Function
Sub RollDice()
Dim Dice(2) As Integer
For i = 0 To 2
Dice(i) = RollD6()
Next
Debug.Print("Dice: " & Dice(0) & " " & Dice(1) & " " & Dice(2))
Debug.Print("Sum: " & Dice(0) + Dice(1) + Dice(2))
End Sub