我有这段代码:
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。当它向M8
添加1时,我希望它返回到顶部,并使用新值M8
重复if语句。
答案 0 :(得分: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
答案 1 :(得分: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