如果转到else,如何使IF语句重复它

时间:2016-06-15 13:35:04

标签: excel vba loops statements

我有这段代码:

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语句。

2 个答案:

答案 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