简体   繁体   中英

VBA Word - iterate through all paragraphs in document in reverse

Problem in short: I need to iterate through all paragraphs in reverse order. I am currently using a For Each loop:

For Each Paragraph in ActiveDocument.Paragraphs
    ' looping code
Next

Why I need to do this: I have an export from a tool which incorrectly formats list elements. I need to go through and set all of these elements to the 'List' word style.

I have this part working using the various ListFormat properties on the paragraph. the problem is that the lists just continue, they dont retain when a list restarts. I end up with the list number being aaaaa. then bbbbb. etc.

I intended to use the ListFormat.ListValue property to determine when to restart the list (would restart when this value = 1), but this wont work, as when you transition one paragraph element to the new 'List' type, the following paragraph automatically resets the ListFormat.ListValue to 1 as well. If I can loop through paragraphs in reverse this will no longer be a problem.

Instead of using a For Each loop, iterate through the paragraphs by index, and you can easily loop from the last paragraph to the first with Step -1 .

Sub Test()
    Dim i As Long
    For i = ActiveDocument.Paragraphs.Count To 1 Step -1
         ActiveDocument.Paragraphs(i).... ' do whatever you want with each paragraph
    Next i
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM