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.
Sub Macro1()
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:
Sub Macro2() 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 pageThis.Delete Else MsgBox "Only one page in document; cannot delete." Exit Do End If Else lngPageIndex = lngPageIndex + 1 End If Loop Else MsgBox "No document is active." End If End Sub