2016-06-15 34 views
0

我有這樣一段代碼:如何使一個IF語句重複itslef,如果去別的

If IsEmpty(Cells(8, M8 + 9).Value) And IsEmpty(Cells(12, M8 + 9).Value) Then 
    Sheets("Sheet3").Cells(8, M8 + 9).Value = info 
    Sheets("Sheet3").Cells(12, M8 + 9).Value = "--------------" 
    Sheets("Sheet3").Range(Cells(8, M8 + 9), Cells(12, M8 + 9)).Interior.Color = RColor 
    M8 = M8 + 1 
Else 
    M8 = M8 + 1 
End If 

我想知道是否有一種方法是,當第一條件沒有被滿足,轉到Else分支向M8變量添加1。當它加1到M8我希望它回到頂部,並重復if語句,新值爲M8

+0

我想邊說GoTo'說法是你在尋找什麼。如果你沒有在else中設置你的值,那麼if語句最終會通過,它將永遠循環。 –

+0

你應該重新命名'M8'來一些有意義的東西。如果你有'M7','M6','M5','M4','M3','M2'和'M1',你可能需要一個數組而不是數字變量。通常當你想到「我想重複某件事直到滿足條件」時,你需要的是一個循環。 –

回答

2

請勿使用If?這將循環直到指定的條件不再爲真;但加里上面提到的有可能會進入一個死循環,所以我增加了一個附加條件,打破循環,如果它繼續進行100次迭代

iTried = 0 
While IsEmpty(Cells(8, M8 + 9).Value) And IsEmpty(Cells(12, M8 + 9).Value) = True And iTried <=100 
    Sheets("Sheet3").Cells(8, M8 + 9).Value = info 
    Sheets("Sheet3").Cells(12, M8 + 9).Value = "--------------" 
    Sheets("Sheet3").Range(Cells(8, M8 + 9), Cells(12, M8 + 9)).Interior.Color = RColor 
    M8 = M8 + 1 
Wend 
' Now check WHY the loop ended... if the cells are empty and the counter is >100 throw a msgbox 
If IsEmpty(Cells(8, M8 + 9).Value) And IsEmpty(Cells(12, M8 + 9).Value) = True And iTried >100 Then 
    MsgBox "Too many tries; gave up!" 
End If 
+2

循環不會是無止境的。如果'M8'是一個'Integer',它的值會達到32768就會溢出。如果它是一個Long,它將會花費一點時間,但它最終會溢出。 –

+1

沒有想到這是誠實的,但我仍然寧願自己控制它的退出點,謝謝澄清 – Dave

+0

我upvoted這個答案作爲循環是首選/更好的方法。 –

2

你需要從另一個方向過來,在這。如果您需要M8以滿足特定的條件,確保滿足條件,你做任何事情之前

Dim aborted As Boolean 
Do While Not (IsEmpty(Cells(8, M8 + 9).Value) And IsEmpty(Cells(12, M8 + 9).Value)) 
    M8 = M8 + 1 
    If M8 > 100 Then 'Or whatever your "give up" condition is 
     aborted = True 
     Exit Do 
    End If 
Loop 

If Not aborted Then 
    Sheets("Sheet3").Cells(8, M8 + 9).Value = info 
    Sheets("Sheet3").Cells(12, M8 + 9).Value = "--------------" 
    Sheets("Sheet3").Range(Cells(8, M8 + 9), Cells(12, M8 + 9)).Interior.Color = RColor 
End If