如何循環此代碼,以便它會重複啓動?Excel VBA代碼循環
Dim i As Long, j As Long, k As Long
Dim ws As Worksheet
Dim r As Range
Sub StartGame()
Set ws = ThisWorkbook.Sheets("Sheet1")
i = 1: j = 1: k = 1
MoveCar1
End Sub
Sub MoveCar1()
With ws
Set r = .Cells(6, i)
r.Cut
r.Offset(, 2).Insert Shift:=xlToRight
i = i + 1
End With
Wait 1
MoveCar2
End Sub
Sub MoveCar2()
With ws
Set r = .Cells(6, i)
r.Cut
r.Offset(, 2).Insert Shift:=xlToRight
i = i + 1
Set r = .Cells(8, j)
r.Cut
r.Offset(, 2).Insert Shift:=xlToRight
j = j + 1
End With
Wait 1
MoveCar3
End Sub
Sub MoveCar3()
With ws
Set r = .Cells(6, i)
r.Cut
r.Offset(, 2).Insert Shift:=xlToRight
i = i + 1
Set r = .Cells(8, j)
r.Cut
r.Offset(, 2).Insert Shift:=xlToRight
j = j + 1
Set r = .Cells(10, k)
r.Cut
r.Offset(, 2).Insert Shift:=xlToRight
k = k + 1
End With
Wait 1
MoveAllCars
End Sub
Sub MoveAllCars()
For l = 1 To 8
With ws
If i < 9 Then
Set r = .Cells(6, i)
r.Cut
r.Offset(, 2).Insert Shift:=xlToRight
i = i + 1
End If
If j < 9 Then
Set r = .Cells(8, j)
r.Cut
r.Offset(, 2).Insert Shift:=xlToRight
j = j + 1
End If
If k < 9 Then
Set r = .Cells(10, k)
r.Cut
r.Offset(, 2).Insert Shift:=xlToRight
k = k + 1
End If
Wait 1
If i > 8 And j > 8 And k > 8 Then Exit For
End With
Next l
End Sub
Private Sub Wait(ByVal nSec As Long)
nSec = nSec + Timer
While nSec > Timer
DoEvents
Wend
End Sub
該代碼使得細胞(A; 6)(A 8)(A; 10)移動闡述,並且當它們到達細胞(I; 6)(I; 8)(我; 10)他們停下來。
是否有可能循環這段代碼,所以它會一遍又一遍地重複?
VBA有超過六個可用的循環結構。你試過了哪一個? –
我知道,我試過「循環直到」,但我不知道如何應用它...... – Faux
你必須澄清你的意思是「循環這段代碼」,並更好地描述你試圖實現的行爲。您在此代碼中使用'For ... Next'和'While ... Wend'循環,因此我認爲您瞭解循環計數器和條件的概念。 –