Mayur
Mayur

Reputation: 3097

Inconsistent looping behaviours of For loop in vba

I've written a macro for deleting MS Word 2010 pages as follows-

Sub deleteAlternatePages()
    CurrentPage = Selection.Information(wdActiveEndPageNumber)
    TotalPages = Selection.Information(wdNumberOfPagesInDocument)

    maxLoop = TotalPages - 1

    Dim loopCtr As Integer
    loopCtr = (maxLoop / 2)

    For i = 1 To loopCtr
        boolDelete = Selection.Information(wdActiveEndPageNumber)
        Call deleteOnePage
        CurPage = Selection.Information(wdActiveEndPageNumber)
        Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext, Count:=1
    Next

End Sub

The loop doesn't work properly when I run the macro from word. But, works properly when I debug the code.

Upvotes: 1

Views: 532

Answers (1)

pinkfloydx33
pinkfloydx33

Reputation: 12749

This is just a hunch, but I bet you are deleting pages you don't intend to? Instead of looping UP, loop backwards

 For i =loopCtr to 1 step -1

In your loop, if you deleted a page, the rest of the pages get moved up a page and will have incorrect page numbers as you continue to check them forward. If you delete from the end first, the pages at the front won't be messed with

Upvotes: 6

Related Questions