我是VBA的新手,我现在正在使用以下代码:
Do
monsterFinalDmg = monsterDmgFunction((Int(2 * Rnd)), ((Int((6 * Rnd) + 1))), ( ((Int(2 * Rnd)) * 8)), ((Int((26 * Rnd) + 75)) / 100))
currentPlayerHP = (currentPlayerHP - monsterFinalDmg)
playerFinalDmg = playerDmgFunction((Int(2 * Rnd)), ((Int((8 * Rnd) + 1))), ((( Int(2 * Rnd)) * 10)), ((Int((16 * Rnd) + 70)) / 100))
currentMonsterHP = (currentMonsterHP - playerFinalDmg)
Loop Until currentMonsterHP <= 0 Or currentPlayerHP <= 0
If currentMonsterHP >= currentPlayerHP Then
Sheets("Sheet3").Range("A1").Value = monsterWinner
Exit Sub
Else
Sheets("Sheet3").Range("A1").Value = playerWinner
Exit Sub
我想在Sheet上指定一系列单元格(B2:B11),这个Do循环将其结果打印到每个单元格而不仅仅是A1。
答案 0 :(得分:0)
以下是您可以扩展的示例:
Dim output As Range
Set output = Sheets("Sheet3").Range("B1")
Do
monsterFinalDmg = monsterDmgFunction((Int(2 * Rnd)), ((Int((6 * Rnd) + 1))), ( ((Int(2 * Rnd)) * 8)), ((Int((26 * Rnd) + 75)) / 100))
currentPlayerHP = (currentPlayerHP - monsterFinalDmg)
playerFinalDmg = playerDmgFunction((Int(2 * Rnd)), ((Int((8 * Rnd) + 1))), ((( Int(2 * Rnd)) * 10)), ((Int((16 * Rnd) + 70)) / 100))
currentMonsterHP = (currentMonsterHP - playerFinalDmg)
output.Value = "value you want to output"
Set output = output.Offset(1)
Loop Until currentMonsterHP <= 0 Or currentPlayerHP <= 0
If currentMonsterHP >= currentPlayerHP Then
Sheets("Sheet3").Range("A1").Value = monsterWinner
Exit Sub
Else
Sheets("Sheet3").Range("A1").Value = playerWinner
Exit Sub
答案 1 :(得分:0)
所以你想重复10个单元格的计算
试试这个:
Public Sub Fight10Times(ByVal currentMonsterHP As Double, ByVal currentPlayerHP As Double)
Dim results() As Variant
'10 trials, with 3 columns. Winner, playerHp, mosterHp
ReDim results(1 To 10, 1 To 3)
Dim i As Integer, monster_hp As Double, player_hp As Double
For i = 1 To 10
'initialize hp values from given
monster_hp = currentMonsterHP
player_hp = currentPlayerHP
' One fight. True of player won, and modifies
' monster_hp, player_hp to final values
If CheckWinner(monster_hp, player_hp) Then
result(i, 1) = playerWinner
Else
result(i, 1) = monsterWinner
End If
results(i, 2) = player_hp
results(i, 3) = monster_hp
Next i
' Setting value on range of cells writes entire array with one operation.
Sheets("Sheet3").Range("B2").Resize(10, 3).Value = results
End Sub
' Arguments are byref because function modifies them and we want to keep the results
Public Function CheckWinner(ByRef currentMonsterHP As Double, ByRef currentPlayerHP As Double) As Boolean
While currentMonsterHP > 0 And currentPlayerHP > 0
monsterFinalDmg = monsterDmgFunction((Int(2 * Rnd)), ((Int((6 * Rnd) + 1))), (((Int(2 * Rnd)) * 8)), ((Int((26 * Rnd) + 75)) / 100))
currentPlayerHP = (currentPlayerHP - monsterFinalDmg)
playerFinalDmg = playerDmgFunction((Int(2 * Rnd)), ((Int((8 * Rnd) + 1))), (((Int(2 * Rnd)) * 10)), ((Int((16 * Rnd) + 70)) / 100))
currentMonsterHP = (currentMonsterHP - playerFinalDmg)
WEnd
'True if player wins
CheckWinner = currentPlayerHP > currentMonsterHP
End Function
将所需的所有值放入Variants
数组并使用Range().Value =
赋值的技巧。