VBA Code to Export a Worksheet as a Word Document

UncleBajubjubs

Board Regular
Joined
Jul 11, 2017
Messages
111
Office Version
  1. 2010
Hello, I have a workbook with one worksheet which is intended to gather data from the other sheets, and then be exported as a word document. I don't have much experience with this, so i copied some code I found online:
Code:
Sub export_excel_to_word()
    Set obj = CreateObject("Word.Application")
    obj.Visible = True
    Set newObj = obj.Documents.Add
    ActiveSheet.UsedRange.Copy
    newObj.Range.Paste
    Application.CutCopyMode = False
    obj.Activate
    newObj.SaveAs Filename:=Application.ActiveWorkbook.Path & "" & ActiveSheet.Name
End Sub

But this gives me "Unexpected End Sub" on the first line. Any ideas, or just alternate code which will do what I need? Thanks!
 
Last edited by a moderator:
I commented out the line
Code:
  .SaveAs2 Application.ActiveWorkbook.Path & "/" & ActiveSheet.Name & ".docx", 12, , False

As it was giving me type mismatch, but otherwise it all works.
Oops - a comma was missing. Try:
Code:
.SaveAs2 Application.ActiveWorkbook.Path & "/" & ActiveSheet.Name & ".docx", 12, , , False ' 12 = wdFormatXMLDocument
Original code updated.
I was also trying to set the line and paragraph spacing, it seems to automatically put large spacing in.
In that that case, since Word's default for an empty document is to use the 'Normal' Style, all you should need to do is insert:
Code:
    'Spacing defaults
    With .Styles("Normal").ParagraphFormat
      .SpaceBefore = 0
      .SpaceAfter = 0
      .LineSpacingRule = 0 'wdLineSpaceSingle
    End With
before:
'Paste Data
 
Upvote 0

Excel Facts

Create a chart in one keystroke
Select the data and press Alt+F1 to insert a default chart. You can change the default chart to any chart type

Forum statistics

Threads
1,223,786
Messages
6,174,547
Members
452,571
Latest member
MarExcelTips

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top