Search code examples
excelvbaoutlookms-word

How do I center an Excel table pasted into Outlook with VBA?


I have a formatting issue with one section of my code.

This does everything I need except center alignment:

'Copy contents

    Sheets("Tables").Select
    Range("J6:R145").Select
    Range("J6").Activate
    Selection.Copy

'Open new mail item

    Dim outlookApp As Object
    Set outlookApp = CreateObject("Outlook.Application")
    Set outMail = outlookApp.CreateItem(0)
   
'Get Word editor

    outMail.Display
    Dim wordDoc As Object
    Set wordDoc = outMail.GetInspector.WordEditor
   
'Paste as image
   
    wordDoc.Range.PasteAndFormat Type:=wdChartPicture
    wordDoc.Range.Select
    Selection.Rows.Alignment = wdAlignRowCenter

Current Result: Failed Debug Step
enter image description here

Here's what I've plugged in so far:

Selection.PageSetup.CenterHorizontally = True
Selection.HorizontalAlignment = xlCenter
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter

and the above-listed Rows.Alignment.

All have failed out at this line rather than centering the object.

Also how do I keep it from deleting the email signature when it pastes?


Solution

  • Try this

    Public Sub pastetable()
    'Copy contents
    
        Sheets("Tables").Select
        Range("J6:R145").Select
        Range("J6").Activate
        Selection.Copy
    
    'Open new mail item
    
        Dim outlookApp As Object
        Set outlookApp = CreateObject("Outlook.Application")
        Set outMail = outlookApp.CreateItem(0)
       
    'Get Word editor
    
        outMail.Display
        Dim wordDoc As Object
        Set wordDoc = outMail.GetInspector.WordEditor
       
    'Paste as image
        wordDoc.Range.InsertParagraphBefore 'Create new empty paragraph before signature
        wordDoc.Paragraphs.first.Range.PasteAndFormat Type:=wdChartPicture
        
        With wordDoc.Tables(1).Rows
            .WrapAroundText = 0 'If this is true does not work
            .Alignment = 1
        End With
    
    End Sub