在Select Case语句中循环没有Do错误

时间:2017-10-14 00:56:05

标签: excel-vba do-loops select-case vba excel

运行此代码时,出现“无需循环”的错误。我想如果选择“case vbno”然后它返回到原始输入框。如果用户选择“case vbyes”我希望它突出显示然后单元格然后循环返回以执行并返回到原始输入框。如果选择取消,我希望它完全退出。

Sub find_highlight3()
    Dim w As Variant
    Dim FoundCell As Range
    Dim ans As String

    Do

        w = InputBox("What to find?")

        Cells.Find(What:=(w), After:=ActiveCell, LookIn:=xlFormulas, _
            LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False).Activate
        With Selection.Interior

            Select Case MsgBox("Hellow", vbYesNoCancel)

                Case vbNo

    Loop

                Case vbYes

                   .ColorIndex = 6
                   .Pattern = xlSolid
                   .PatternColorIndex = xlAutomatic

    Loop

                Case vbCancel

            End Select

        End With
End Sub

1 个答案:

答案 0 :(得分:0)

以下代码应该做你想要的,同时仍然保持代码的每个“块”的完整性。

Sub find_highlight3()
    Dim w As Variant
    Dim FoundCell As Range
    Dim ans As String

    Do
        w = InputBox("What to find?")

        Cells.Find(What:=(w), After:=ActiveCell, LookIn:=xlFormulas, _
            LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False).Activate

        Select Case MsgBox("Hellow", vbYesNoCancel)

            Case vbNo

            Case vbYes    
                With Selection.Interior
                    .ColorIndex = 6
                    .Pattern = xlSolid
                    .PatternColorIndex = xlAutomatic
                End With

            Case vbCancel    
                Exit Do

        End Select
    Loop
End Sub

注意:如果Activate与任何内容不匹配(Find无效),您的Nothing.Activate语句将失败,但这是另一天的问题。