Avoiding infinite loops while searching for text.

JohnCTX 636 Reputation points
2021-03-17T10:29:31.03+00:00

I am having too many issues while performing loops. For example, program stops at a character as it exits the loop.
Sub MyMacro()
lngX = 1

    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "|"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    'This triggers an infinite loop and needs to be fixed.
    Do Until Selection.Text = "{"
        Selection.HomeKey
        Selection.TypeText "||||||"
    Loop
    Selection.Find.Execute

End Sub

All users are welcome to assist me in solving this issue.

Regards,

JohnCTX

Developer technologies | Visual Basic for Applications
{count} votes

1 answer

Sort by: Most helpful
  1. Nothing Left To Lose 396 Reputation points
    2021-03-17T11:16:40.227+00:00

    re: find stuff

    Below is my Find code. It checks for no answer or a repeat find and exits.
    Returns a message with the cell location of the found cells.
    Modify as needed.
    '---
    Sub FindSomeThingExample()
    'Nothing Left to Lose - March 2021
    Dim SearchFor As Variant
    Dim rCell As Excel.Range
    Dim firstAddress As String
    Dim strMessage As String

    SearchFor = "|"
    'Change to Excel.Selection.Cells if preferred
    With ThisWorkbook.Worksheets(1).Cells
    Set rCell = .Find(SearchFor, LookIn:=xlValues)
    If Not rCell Is Nothing Then
    firstAddress = rCell.Address 'stopping point
    strMessage = rCell.Address(external:=True) 'includes sheet name
    Do
    Set rCell = .FindNext(rCell)
    'stop searching if
    If rCell Is Nothing Or rCell.Address = firstAddress Then Exit Do
    'accumulate locations
    strMessage = strMessage & vbCr & rCell.Address(external:=True)
    Loop
    End If
    End With
    If VBA.Len(strMessage) Then
    VBA.MsgBox strMessage
    Else
    VBA.MsgBox "Nothing found "
    End If
    End Sub
    '---

    NLtL
    https://1drv.ms/u/s!Au8Lyt79SOuhZ_2VvKCLZxz9iwI?e=vnEabM
    Free: Custom_Functions, Professional_Compare and more

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.