陷入无限循环搜索文本框

时间:2015-04-09 19:21:52

标签: excel vba excel-vba

我的代码搜索整个工作表,搜索与输入的短语匹配的文本框。按yes将转到下一个响应,该短语no将复制当前文本框。我的问题是它不会搜索整个工作表,而是在一个工作表中循环,直到我按否复制。我是VBA的新手,所以请任何帮助都会感激不尽。

Sub FindResponse()
    Dim rStart As Range
    Dim shp As Shape
    Dim sFind As String
    Dim sTemp As String
    Dim Response
    Dim obj As New DataObject
    Dim ws As Worksheet




    sFind = InputBox("Search for?")
    If Trim(sFind) = "" Then
        MsgBox "Nothing entered"
        Exit Sub
    End If
    Set rStart = ActiveCell

    For Each ws In Worksheets


    For Each shp In ActiveSheet.Shapes
    With shp
        sTemp = shp.TextFrame.Characters.Text
        If InStr(LCase(sTemp), LCase(sFind)) <> 0 Then
            shp.Select
            Response = MsgBox( _
              prompt:=shp.Name & vbCrLf & _
              sTemp & vbCrLf & vbCrLf & _
              "Yes to see other matches: No to copy text", _
              Buttons:=vbYesNo, Title:="Continue?")
            If Response <> vbYes Then

            obj.SetText sTemp
            obj.PutInClipboard

                Exit Sub

            End If

        End If
        End With
    Next shp

    Next ws

 On Error GoTo 0

    MsgBox "Value not found"

End Sub

1 个答案:

答案 0 :(得分:1)

你的循环结构是这样的:

For Each ws In Worksheets
  For Each shp In ActiveSheet.Shapes
    With shp
      ...
    End With
  Next shp
Next ws

正如您可能在仔细观察之后猜测的那样,它保留在同一张纸上的原因是,在您的内循环中,您循环遍历ActiveSheet.Shapes,而不是ws.Shapes,我怀疑是你打算做的。

我听到循环是无限的,我感到有点惊讶 - 它是否只是循环通过你调用它的工作表与工作簿中的工作表相同的次数?