I am trying to get a macro that will delete all of the pages in the current document that have less than 5 layers. I tried the code below, but it doesn't work. I'm new to VBA so this might be way off.
Dim p As PageDim i& For i = 1 To ActiveDocument.Pages.Count Set p = ActiveDocument.Pages(i) If ActivePage.Layers.Count < 5 Then ActivePage.Delete Next i End Sub
try code below
Dim p As PageDim i&For i = 1 To ActiveDocument.Pages.CountSet p = ActiveDocument.Pages(i)
p.activateIf ActivePage.Layers.Count < 5 Then ActivePage.DeleteNext iEnd Sub
I think you will have problems with that, Mek.
If the macro is deleting pages, then the macro will eventually try to use a page index that is no longer valid.
I have made the same type of mistake when deleting shapes from a ShapeRange.
I would use Do While or Do Until, and then Loop until I had gotten through all of the pages. The condition for continuing to loop would be checking where I was with respect to the current number of pages in the document, and only increment the index when I had checked a page and not deleted it.
Perhaps something like this:
Dim lngPageIndex As Long
Dim pageThis As Page
If Not ActiveDocument Is Nothing Then
lngPageIndex = 1
Do Until lngPageIndex > ActiveDocument.Pages.Count
Set pageThis = ActiveDocument.Pages(lngPageIndex)
If pageThis.Layers.Count < 5 Then
If ActiveDocument.Pages.Count > 1 Then
MsgBox "Only one page in document; cannot delete."
lngPageIndex = lngPageIndex + 1
MsgBox "No document is active."
Worked perfectly! Thanks so much!
Sub delPagesLess5() Dim p As Page For Each p In ActiveDocument.Pages If p.Layers.Count < 5 Then p.Delete End If Next pEnd Sub
That's more elegant than mine. I would still want to add a check to avoid trying to delete the only remaining page.