none
Do...Until loop structures within For Each...Next structure RRS feed

  • Question

  • Hello,

    I would like to know more examples regarding Do...Until loop structures within a For Each...Next structure.

    For example:

    for each c in word.

      Dim Bolds As VBA.Collection
      Dim Word As Word.Range
      Dim Bold As Variant
      Set Bolds = New VBA.Collection
      For Each Word In Selection.Words
        If Word.Font.ColorIndex = wdRed And Not (Word.Font.Bold Or Word.Font.Italic) Then
            NumCcpts = 0
            Bolds.Add Word.Text
            strX = Word.Text                                                                'Put bold text in parameter to reserve in memory at runtime.
            Print #1, strX;
        End If
        If Word.Font.ColorIndex = wdBlack Then
            Bolds.Add Word.Text
            strX = Word.Text
            Print #1, strX;
        End If
        If Word.Font.ColorIndex = wdRed And Word.Font.Bold Then
            Bolds.Add Word.Text
            strX = Word.Text
            Print #1, strX;
        End If
        If Word.Font.Italic And Word.Font.ColorIndex = wdRed Then
            Do Until Word.Font.Bold    'This may trigger an infinite loop at runtime.
                intX = intX + 1
                Print #2, intX
            Loop
        End If
      Next Word
    
      
      Set Word = Nothing
      
      For Each Bold In Bolds
        Debug.Print Bold
      Next Bold
      
      Set Bold = Nothing
      Set Bolds = Nothing
      Close
      

    How could I fix this code snippet?  Can anyone provide me examples?

    Regards,

    JohnDBCTX


    jp

    Friday, March 30, 2018 12:35 PM

Answers

  • I don't understand what you are attempting to do with the following that goes into an infinite loop. It is simply looping on the same word.

         Do Until Word.Font.Bold    'This may trigger an infinite loop at runtime.
                intX
    = intX + 1
                Print
    #2, intX
         Loop

    If you are looking for a bold character within the word then you should use code like the following. It will test each character and will only run for the number of characters in the word.

                'Following will loop through each character in the word
                Dim char As Range
                For Each char In Word.Characters
                    If char.Font.Bold Then
                        Debug.Print char    'For testing. Prints the bold character to Immediate Window.
                    End If
                Next char


    Regards, OssieMac

    • Marked as answer by JohnDBCTX Sunday, April 15, 2018 7:56 PM
    Sunday, April 1, 2018 2:16 AM