Microsoft Word Copy Format VBA (visual basic for applications)

Microsoft Word Copy  Format VBA (visual basic for applications)

CopyFormat

Method copies formatting of first character from the selected text or contents and applied over destination. In this article we will copy format of existing formatted text to another paragraph using Visual Basic for Application code:

Refer above screenshot where I have two paragraphs, the first paragraph has VBAOVERALL.COM text highlighted in Yellow color and Bold text. Lets write some code which will copy the same formatting and paste it over entire paragraph 2

Code

Public Sub CopyPasteFormat()
     'Bind document object reference
    Dim oDocument As Document
    Set oDocument = ActiveDocument
    
    'Bind selection object reference
    Dim oSelection As Selection
    Set oSelection = Selection
    
    'Copy format
    oSelection.CopyFormat
    
    'Select second para
    oDocument.Paragraphs(2).Range.Select
    
    'Paste format
    oSelection.PasteFormat
    
    'Memory cleanup
    Set oSelection = Nothing
    Set oDocument = Nothing
End Sub

Output

Leave a Reply

Your email address will not be published. Required fields are marked *