Apply Page Setup Columns settings to selected text only not entire document

177 views Asked by At

I'm trying to create a macro in microsoft word that can apply different number of page columns in different parts of the same page, guided by selected text.

When I do it manually, its possible because I can choose the Apply to: Selected text option, which does not appear in VBA

How can I have the "Apply to: Selected text " option set in VBA?

The recorded VBA macro has no Apply to: Selected text " option

Here is the recorded VBA macro code

Sub Macro1()

    With Selection.PageSetup.TextColumns 
    
        .SetCount NumColumns:=2 
    
        .EvenlySpaced = True 
    
        .LineBetween = True 
    
        .Width = CentimetersToPoints(11.36) 
    
        .Spacing = CentimetersToPoints(1.27) 
    
    End With 

End Sub
1

There are 1 answers

0
Timothy Rylatt On

If you look at what happens in your document when you apply the columns dialog to the selected text, you will see that continuous section breaks are added before and after the selection.

This is because page setup is a property of the section, not the selection.

Sub ApplyColumnsToSelection()
    Dim currSection As Long, newSection As Section
    'obtain index of current section so we know which section to add columns to
    currSection = Selection.Information(wdActiveEndSectionNumber)
    Dim rng As Range
    Set rng = Selection.Range
    'add section breaks before and after the selection
    rng.Characters.First.InsertBreak wdSectionBreakContinuous
    rng.Collapse wdCollapseEnd
    rng.InsertBreak wdSectionBreakContinuous
    'apply columns to new section
    Set newSection = ActiveDocument.Sections(currSection + 1)
    With newSection.PageSetup.TextColumns
        .SetCount NumColumns:=2
        .EvenlySpaced = True
        .LineBetween = True
    End With
End Sub