将随机骰子的值放入数组(VBA)

时间:2017-04-23 02:31:53

标签: arrays excel vba dice

我试图找出如何创建三个给定函数返回值的数组。我没有把数据放到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

1 个答案:

答案 0 :(得分:3)

每个骰子不需要单独的功能,也不需要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