Search code examples
arraysexcelvbadice

Put the value of random dice into an array (VBA)


I am trying to figure out how I can create an array of the three given functions returned values. I am not putting the data into excel anywhere so I can't use "range". I believe there is a solution however I haven't been able to figure it out yet.

'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

Solution

  • You don't need a separate function for each die, and you don't need ByRef. Do this:

    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