Question

I need VBA code to delete all sections(pages) except first in Word document

For this I use below code.

For Each oSec In ActiveDocument.Sections
    If oSec.Index <> 1 Then
        oSec.Range.Delete
    End If   
Next oSec

This works but does not delete second section only removes its content. If I removes if condition in code it removes content of first page.

I want to preserve content of first page.

Please tell me where I am making mistake.

Was it helpful?

Solution

When deleting you need to include section break marks. Try to change this line:

oSec.Range.Delete

into this one:

ActiveDocument.Range(oSec.Range.Start - 1, oSec.Range.End).Delete

BTW, you should not think that page=section, they are different type of document units.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top