0

I have supplied my code below. Right now, there is an error in my code. I want the page number to list 1,2,3,4,5 in order for each page, but it is instead listed like 5,5,5,5,5.

It may be because of the code I added:

Dim PageNum As String
            PageNum = CStr(PageCnt)
            TOCEntry.Text = PageNum + " -------- " + PageObj.Name
 

Here's the complete code:

Option Explicit

Sub TableOfContents()
     ' creates a shape for each page in the drawing on the first page of the drawing
     ' then add a dbl-clk GoTo to each shape so you can double click and go to that Page
     
    Dim PageObj   As Visio.Page
    Dim TOCEntry  As Visio.Shape
    Dim CellObj   As Visio.Cell
    Dim PosY      As Double
    Dim PageCnt   As Double
     
     ' ActiveDocument.Pages.Count will give the number of pages, but we are interested
     ' the number of foreground pages
    PageCnt = 0
    For Each PageObj In ActiveDocument.Pages
        If PageObj.Background = False Then PageCnt = PageCnt + 1
    Next
     
     ' loop through all the pages
    For Each PageObj In ActiveDocument.Pages
        If PageObj.Background = False Then ' Only foreground pages
             
             ' where to put the entry on the page?
            PosY = (PageCnt - PageObj.Index) / 4 + 1
             
             ' draw a rectangle for each page to hold the text
            Set TOCEntry = ActiveDocument.Pages(1).DrawRectangle(1, PosY, 4, PosY + 0.25)
             
             
             
             
             ' write the page name in the rectangle
            Dim PageNum As String
            PageNum = CStr(PageCnt)
            TOCEntry.Text = PageNum + " -------- " + PageObj.Name
            
            
             
             ' add a link to point to the page to you can just go there with a Double Click
            Set CellObj = TOCEntry.CellsSRC(visSectionObject, visRowEvent, visEvtCellDblClick) 'Start
            CellObj.Formula = "GOTOPAGE(""" + PageObj.Name + """)"
             
        End If
    Next
     
     'Clean Up
    Set CellObj = Nothing
    Set TOCEntry = Nothing
    Set PageObj = Nothing
End Sub
Brian M Stafford
  • 8,483
  • 2
  • 16
  • 25
weaver
  • 1

2 Answers2

0

You've set PageCnt to the number of non-Background pages, but then used that total as your page index. You don't need to count the number of pages, so remove the first loop and set PageCnt to 1 initially, then increment it after you set the CellObj.Formula value.

Paul Herber
  • 1,150
  • 1
  • 7
  • 12
  • I replaced it with this `For Each PageObj In ActiveDocument.Pages If CellObj.Formula = True Then PageCnt = PageCnt + 1 Next` I am getting an error message, and it doesn't seem to work. I apologize, I am new to VBA coding. – weaver Apr 12 '21 at 12:57
0

You are getting 5,5,5,5,5 because of this line:

PageNum = CStr(PageCnt)

To fix this this line should be:

PageNum = CStr(PageObj.Index)

So, it can give you 1,2,3,4,5.