Barry Smith
Barry Smith

Reputation: 319

VBA skips a For loop - why?

I have this VBA code in MS Word Visual Basic Editor;

It is meant to reset the page numbers so that they work consecutively. However, it seems to skip the entire contents of the loop without executing this.

Sub Macro3()
'
' Macro3 Macro
' Test 3
'
Dim GetNumberOfPages

    For IncVar = 1 To GetNumberOfPages
        WordBasic.ViewFooterOnly
        ActiveDocument.AttachedTemplate.BuildingBlockEntries(" Blank").Insert _
            Where:=Selection.Range, RichText:=True
        WordBasic.ViewFooterOnly
        ActiveDocument.AttachedTemplate.BuildingBlockEntries("Plain Number 3"). _
            Insert Where:=Selection.Range, RichText:=True
        ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
        Selection.WholeStory
        With Selection.Sections(IncVar).Headers(IncVar).PageNumbers
            .NumberStyle = wdPageNumberStyleArabic
            .HeadingLevelForChapter = 0
            .IncludeChapterNumber = False
            .ChapterPageSeparator = wdSeparatorHyphen
            .RestartNumberingAtSection = False
            .StartingNumber = 0
        End With
        Selection.WholeStory
        Selection.EscapeKey
        ActiveWindow.ActivePane.View.ShowAll = Not ActiveWindow.ActivePane.View. _
            ShowAll
        Selection.EscapeKey
        Selection.EscapeKey
    Next IncVar
End Sub

Why is this? How can I fix it?

Thanks,

Barry Smith

Upvotes: 1

Views: 298

Answers (3)

JustinJDavies
JustinJDavies

Reputation: 2693

If you use f8 to Step Into... your sequence and check the value of GetNumberOfPages you will see that the GetNumberOfPages = Empty and the entire loop is skipped

Upvotes: 5

Arpit
Arpit

Reputation: 12797

i think you are thinking in that way

Dim GetNumberOfPages as integer = ActiveDocument.BuiltInDocumentProperties(wdPropertyPages) //check the syntax . i'm not sure. 

But forget to initilize the GetNumberOfPages

Upvotes: 1

Peter Albert
Peter Albert

Reputation: 17505

GetNumberOfPages is a variable, which by default is blank.

You first need to assign some value to it, e.g.

Dim numberOfPages as Integer
Dim currentPage as Integer
numberOfPages = ActiveDocument.BuiltInDocumentProperties(wdPropertyPages)
For currentPage = 1 To numberOfPages
    ...
Next currentPage

Upvotes: 3

Related Questions