索引或创建已定义用户定义类型(VBA)的数组

时间:2017-04-25 05:01:24

标签: arrays vba excel-vba user-defined-types excel

所以我希望索引一个在structpairofdice的UDT中定义的变量,或者稍后在代码中擦除静态intRollNum变量的内存。最好是我想对sumdice变量建立索引,虽然我还没有能够弄清楚,非常感谢帮助

    Option Explicit

Type structPairOfDice
    diceOne As Integer
    diceTwo As Integer
    rollNum As Integer
    sumDice As Variant
End Type

'Randomizes the dice between 1 and 6
Function RandomizeDice() As Integer
        RandomizeDice = Application.WorksheetFunction.RandBetween(1, 6)
End Function
Sub RollDice(structDice As structPairOfDice)
    Static intRollNum As Integer
    intRollNum = intRollNum + 1
    With structDice
        .rollNum = intRollNum
        .diceOne = RandomizeDice()
        .diceTwo = RandomizeDice()
        .sumDice = .diceOne + .diceTwo
    End With
End Sub
Sub PrintResults(structDice As structPairOfDice)
    Call RollDice(structDice)
    With structDice
        Debug.Print "Roll #: " & .rollNum
        Debug.Print "Dice: " & .diceOne & ", " & .diceTwo
        Debug.Print "Sum: "; .sumDice
    End With
End Sub
Sub Main()
    Dim structDice As structPairOfDice
    SetThePoint structDice
    'PrintResults structDice
End Sub

1 个答案:

答案 0 :(得分:0)

您可以查看这两个问题,看看您可能更喜欢使用Class而不是UDT:

你可以像这样编写一个类:

clsDice

Option Explicit

Public diceOne As Long
Public diceTwo As Long
Public rollNum As Long
Public sumDice As Long

Public Sub RollDice()
    diceOne = Application.WorksheetFunction.RandBetween(1, 6)
    diceTwo = Application.WorksheetFunction.RandBetween(1, 6)
    sumDice = diceOne + diceTwo
End Sub

Private Sub Class_Initialize()
    RollDice
End Sub

因此,当您创建课程时,会立即调用RollDicerollNum可以设置为您需要的任何内容Public

然后,在标准模块中,您可以执行此操作来“玩游戏”并使用Dictionary来存储骰子每次投掷的结果:

模块1

Option Explicit

Sub PlayGame()

    Dim objDiceDic As Object
    Dim objDice As clsDice
    Dim lngMaxRounds As Long
    Dim lngRound As Long

    ' dictionary for game simulation
    Set objDiceDic = CreateObject("Scripting.Dictionary")

    ' arbitrary number of rounds
    lngMaxRounds = 10
    For lngRound = 1 To lngMaxRounds
        ' creating a new dice class does the rolls for you
        Set objDice = New clsDice
        ' set the rollNum to this round
        objDice.rollNum = lngRound
        ' add the dice object to our throw tracking dictionary
        objDiceDic.Add lngRound, objDice
    Next lngRound

    ' test the simulation output
    For lngRound = 1 To lngMaxRounds
        With objDiceDic(lngRound)
            Debug.Print "Roll #: " & .rollNum
            Debug.Print "Dice: " & .diceOne & ", " & .diceTwo
            Debug.Print "Sum: "; .sumDice
        End With
    Next lngRound

End Sub

因此每个'round'成为字典中的键,其中值是clsDice对象,您还存储了该轮(rollNum)。因此,您可以轻松地使用字典键来访问特定回合的结果,例如

Debug.Print objDiceDic(4).sumDice