[英]how can you make an array save as a new object each time a function is executed and not overwrite my old array
[英]Running counter each time a function is executed (VBA)
我對數組的索引略有掙扎。 我希望數組的上限是函數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
使您的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
您可以使用靜態變量來實現。 靜態變量的值在函數調用之間保持不變。 請參閱下面的解決方案。 多次運行下面的代碼中的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.