首页 > 解决方案 > 退出 If 和 Next For

问题描述

我有一个带有 if 语句的 for next 循环。如果“If 语句”为真,则退出 if 和 next for。这是代码:我想要的是如果 Rng1 不在 Range1 中,那么转到下一个 rng1。我似乎是一个简单的解决方案,但我无法弄清楚。先感谢您。

Sub me_test()

Dim Range1 As Range
Dim Rng1 As Range
Set Range1 = Application.Selection
Set Range1 = Application.InputBox("Please Select Your Range :", xtitledID, Range1.Address, Type:=8)

    For Each Rng1 In Range1
        If Intersect(Rng1, Range("B7:B15")) Is Nothing Then
            MsgBox "Not within the perscribed range." & vbCr & "Please click OK to continue."
        Else
            Rng1.Value = "Good"
        End If
    Next

MsgBox "All Done"

End Sub

标签: excelvba

解决方案


Sub me_test()

    Dim Range1 As Range
    Dim Rng1 As Range

    Set Range1 = Application.Selection

    Set Range1 = Application.InputBox("Please Select Your Range :", xtitledID, _
                                       Range1.Address, Type:=8)

    Set Range1 = Application.Intersect(Range1, ActiveSheet.Range("B7:B15"))

    If Range1 is nothing then
         MsgBox "No valid cells selected!"
    else
         Range1.Value = "Good"
    end if 

End Sub

推荐阅读