Excel to word export vba

This Excel VBA tutorial explains how to export Excel to Word.

You may also want to read:

Export Excel to PDF

In the previous post, I demonstrated how to export Excel to PDF, which is very easy because there is already a built in function to do that (using Save As and choose PDF). However, there is no built in function to export Excel to Word. Fortunately Excel cell is actually a table in Word, we can simply copy the cells and paste to Word. This tutorial explains how to do it automatically using Excel VBA to export Excel to Word.

Excel VBA export Excel to Word (Single Worksheet)

Excel has about 1M rows and 16k columns, we cannot simply export the whole spreadsheet to Word. So the first question to think about is, what Range do we need to export to Word? My recommendation is to export all UsedRange. You may also consider to reset UsedRange before copy as explained in my previous post.

Insert the following Procedure in Excel Module

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

For example, we have the below worksheet

export Excel to Word 01

Run the Macro, and the below new Word document will pop up. The Word document is automatically saved as the Worksheet name under the same folder of the Workbook.

export Excel to Word 02

It is possible that the imported table length is too wide to display in Word, you can also use Word VBA Table.AutoFitBehavior Method to auto fit the table, which has the same effect of AutoFit in Word as below.

export Excel to Word 03

Run the below macro in Word VBA to loop through all tables in Word document to autosize.

Sub autoSizeTbl()
    For Each tbl In ActiveDocument.Tables
        tbl.AutoFitBehavior wdAutoFitContent
    Next
End Sub

Ideally this Macro can be run from Excel VBA, unfortunately I can’t get it work properly.

Excel VBA export Excel to Word (Multiple Worksheets)

Assume that we have Sheet1, Sheet2, Sheet3 in a Workbook “Export.xlsm”, we want to export all three worksheets to a single workbook.

export Excel to Word 04

Insert a Excel Module and paste the below Procedure.

The below Procedure will copy usedRange of each Worksheet to Word and page break by each Worksheet. Finally save and name the Word document as the Workbook name.

Sub export_workbook_to_word()
    Set obj = CreateObject("Word.Application")
    obj.Visible = True
    Set newobj = obj.Documents.Add
    
    For Each ws In ActiveWorkbook.Sheets
        ws.UsedRange.Copy
        newobj.ActiveWindow.Selection.PasteExcelTable False, False, False
        newobj.ActiveWindow.Selection.InsertBreak Type:=7
    Next
        newobj.ActiveWindow.Selection.TypeBackspace
        newobj.ActiveWindow.Selection.TypeBackspace
          
    obj.Activate
    newobj.SaveAs Filename:=Application.ActiveWorkbook.Path & "" & Split(ActiveWorkbook.Name, ".")(0)

End Sub

Run the Macro, a Word document called “Export.docx” pops up. Worksheet1 is pasted in page 1, Worksheet2 is pasted in page 2, Worksheet3 is pasted in page 3.

export Excel to Word 05

export Excel to Word 06

export Excel to Word 07

To copy data from Excel to a Word file using VBA we need to access the word application using Excel VBA. In this tutorial we will learn how to open a word application, add a document and copy-paste data from excel to it.

In this article, we will use the Early Binding method to create an object of word application instead of using the late binding. You can read about it here in detail.

The Process Of Copying Excel Data To A Word File Using Excel VBA

To copy data from excel to a word file using VBA, we first need to open the Word Application of course. Then add a document to it (if you want a new document). Copy data from excel file. Select the paragraph on the doc and paste on it.Finally save and close the document. Each of these steps can be done easily from Excel. You will not need to interact with the Word Document.

Let’s get started with an example without getting any further into theory. Because Iron Man said, «Sometimes you gotta run before you can walk».

Example : Paste Excel Data To Word Using VBA

The below code is an example of how you can copy some range of excel and paste it into a new word document and save it on the drive to use later

'VBA Code To Write to Copy data from Excel to A Document

Sub ExcelToWord()

   'Using Early Binding

    Dim wordApp As Word.Application

    Dim mydoc As Word.Document

        

    

    'Creating a new instance of word only if there no other instances

    Set wordApp = New Word.Application

    

    

    'Making word App Visible

    wordApp.Visible = True

   

    'Creating a new document

    Set mydoc = wordApp.Documents.Add()


    

    'copying the content from excel sheet


    ThisWorkbook.Worksheets("sheet1").Range("A1:g20").Copy


    'Pasting on the document


    mydoc.Paragraphs(1).Range.PasteExcelTable _

                               LinkedToExcel:=False, _

                               WordFormatting:=False, 

                               RTF:=False

    'saving the document

    mydoc.SaveAs2 "MyDoc"

    

    'closing the document

    mydoc.Close

   

    'Emptying the Clipboard 

    CutCopyMode = False

   

End Sub

Explanation of the Code:

Well I have explained each step in the code itself using comments but let’s have some word about the lines we have used in this sub.

  ‘Created variables of word application and document type

    Dim wordApp As Word.Application

    Dim mydoc As Word.Document

Here we have declared two variables of the required types. We can do this because  we have already added the reference to the word application. You can do this by going to tools in menu. Find references option and then look for the word reference.

    ‘Creating a new instance of word only if there no other instances

    Set wordApp = New Word.Application

    ‘Making word App Visible

    wordApp.Visible = True

    ‘Creating a new document

    Set mydoc = wordApp.Documents.Add()

In the first line above, we are intentiating the wordApp variable with an object of type Word.App using the New keyword. This will open the Word Application.

In the second line we are making the word application visible so that we can work with it.

In the next line, we add a new document to the word application using Word.Documents.Add() function. This is stored in the mydoc variable.

    ‘copying the content from excel sheet

    ThisWorkbook.Worksheets(«sheet1»).Range(«A1:G20»).Copy

Here we are simply copying a range from excel. You must have done it before. It is stored on the clipboard.

    ‘Pasting on the document

    mydoc.Paragraphs(1).Range.PasteExcelTable _

                               LinkedToExcel:=False, _

                               WordFormatting:=False, 

                               RTF:=False

We are using the PasteExcelTable method of Paragraph.Range class of mydoc to paste data from clipboard.

 ‘saving the document

    mydoc.SaveAs2 «MyDoc»

    ‘closing the document

    mydoc.Close

    ‘Emptying the Clipboard 

    CutCopyMode = False

We are saving the document with the name MyDoc. Then we close the document using the Close function. Finally we release the clipboard to be used by others.

So yeah guys, this is how you can create a new Word document and copy Excel data to it using VBA. I have not gone into details as it would make the article exhaustingly long. This was only to learn how you can paste to a word document through Excel. I hope it helped you understand the process. If you have any questions regarding this article, you can contact me through the comments section below.

Related Articles:

Getting Started With Excel VBA UserForms| I will explain how to create a form in excel, how to use VBA toolbox, how to handle user inputs and finally how to store the user inputs. We will go through these topics using one example and step by step guide.

VBA variables in Excel| VBA stands for Visual Basic for Applications. It is a programming language from Microsoft. It is used with Microsoft Office applications such as MSExcel, MS-Word and MS-Access whereas VBA variables are specific keywords.

Excel VBA Variable Scope| In all the programming languages, we have variable access specifiers that define from where a defined variable can be accessed. Excel VBA is no Exception. VBA too has scope specifiers.

ByRef and ByVal Arguments | When an argument is passed as a ByRef argument to a different sub or function, the reference of the actual variable is sent. Any changes made into the copy of the variable, will reflect in the original argument.

Delete sheets without confirmation prompts using VBA in Microsoft Excel | Since you are deleting sheets using VBA, you know what you are doing. You would like to tell Excel not to show this warning and delete the damn sheet.

Add And Save New Workbook Using VBA In Microsoft Excel 2016| In this code, we first created a reference to a workbook object. And then we initialized it with a new workbook object. The benefit of this approach is that you can do operations on this new workbook easily. Like saving, closing, deleting, etc

Display A Message On The Excel VBA Status Bar| The status bar in excel can be used as a code monitor. When your VBA code is lengthy and you do several tasks using VBA, you often disable the screen update so that you don’t see that screen flickering.

Turn Off Warning Messages Using VBA In Microsoft Excel 2016| This code not only disables VBA alerts but also increases the time efficiency of the code. Let’s see how.

Popular Articles:

50 Excel Shortcuts to Increase Your Productivity | Get faster at your task. These 50 shortcuts will make you work even faster on Excel.

The VLOOKUP Function in Excel | This is one of the most used and popular functions of excel that is used to lookup value from different ranges and sheets. 

COUNTIF in Excel 2016 | Count values with conditions using this amazing function. You don’t need to filter your data to count specific values. Countif function is essential to prepare your dashboard.

How to use SUMIF Function in Excel | This is another dashboard essential function. This helps you sum up values on specific conditions.

I have the following code found from this web site. It works almost, except that it export the date into a form in Word document. Instead, I would like to have paragraphs, keeping the original font, size and color in excel. Could anyone help? Very much appreciated!

Sub Export_Excel_To_Word()

Dim wdApp As Object
Dim wd As Object

On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
    Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0

Set wd = wdApp.Documents.Add

wdApp.Visible = True



Sheets("sheet1").Activate
Set Rng = ThisWorkbook.ActiveSheet.Range("A2:F21")

Rng.Copy

   With wd.Range
        .Collapse Direction:=wdCollapseStart                  'Slutet av dokumentet
        .InsertParagraphAfter                                 'Lagg till rad
        .Collapse Direction:=wdCollapseStart                  'Slutet av dokumentet
        .PasteSpecial xlPasteFormats, False, False            'Paste with format

    End With

End Sub

asked Mar 14, 2017 at 18:14

Vivian Yu's user avatar

5

It’s pretty simple, you’re using the pasteSpecial method with misplaced parameters. That induced me in error in the beginning. Try this to paste pure unformatted text:

.PasteSpecial DataType:=2 ' wdPasteDataType.wdPasteText

Or to keep the formats of fonts,

.PasteSpecial DataType:=1 ' wdPasteDataType.wdPasteRtf

To replace the tabs with single space after the paste:

With wd.Range
    .Collapse Direction:=wdCollapseStart
    .InsertParagraphAfter
    .Collapse Direction:=wdCollapseStart
    .PasteSpecial DataType:=2
    With .Find
        .ClearFormatting
        .Text = vbTab
        .Replacement.ClearFormatting
        .Replacement.Text = " "
        .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
    End With
End With

answered Mar 14, 2017 at 19:19

A.S.H's user avatar

A.S.HA.S.H

29k5 gold badges22 silver badges49 bronze badges

8

The easiest alternative that I can think of is to paste the Excel Range and convert the table to text:

ThisWorkbook.Sheets("sheet1").Range("A2:F21").Copy

wdApp.Selection.Paste

wdApp.DefaultTableSeparator = " "

wdApp.Selection.Previous(15).Rows.ConvertToText 

answered Mar 14, 2017 at 20:45

Slai's user avatar

SlaiSlai

21.8k5 gold badges43 silver badges52 bronze badges

3

In this article I will explain how you can write data from an excel workbook to a word document. The first step in doing this is to determine where the code is going to be written. There are 3 options:

  1. In the excel workbook
  2. In the word document
  3. In a 3rd file

I will only consider the first two cases in this article.


Example 1, Excel VBA:

Lets assume we have an excel workbook with the following data:

Word-Excel VBA, Excel Data

Lets assume we are going  to write the code in the excel workbook.

Step 1:

The first step would be to automate a word document.  In the article below I’ve explained there are 2 methods for this.

  1. Early binding
  2. Late binding

To prevent compatibility issues I will be using late binding in this example:

  • VBA, Automating Word From Excel

The function below will automate a word document and make it visible:

Sub main()
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.documents.Add()
End Sub

Step 2:

The code below will write data from the excel sheet to the word document:

Dim i As Integer
Dim strValue As String
For i = 1 To 5
    'bring focus to the document created
    objDoc.Activate
    'read the value from the cell
    strValue = Cells(i + 1, 1)
    'write the value to the document
    objWord.Selection.TypeText Text:=strValue
    'move to the next line
    objWord.Selection.TypeParagraph
Next i

Complete Version:

Below you can see the complete code. It automates a word document and writes the values from the cells B2:B6 to it:

Option Explicit
Sub main()
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.documents.Add

Dim i As Integer
Dim strValue As String
For i = 1 To 5
    'bring focus to the document created
    objDoc.Activate
    'read the value from the cell
    strValue = Cells(i + 1, 1)
    'write the value to the document
    objWord.Selection.TypeText Text:=strValue
    'move to the next line
    objWord.Selection.TypeParagraph
Next i
End Sub

Result:

Word Excel, VBA, Result


Example 2, Word VBA:

In this example the code will be written inside a word document. Therefore the excel workbook will be automated.

Step 1:

The first step would be to get the path of the excel workbook from the user. This can be done using an open file dialog. I have covered this topic in the article below:

  • Excel VBA, Open File Dialog

Although the article was written for excel, the concept can be used in VBA for Word too. The code below will display an open file dialog and ask the user to select the path of the file to open. The path will be stored in the variable strPath:

Sub Example2()
Dim intChoice As Integer
Dim strPath As String

'only allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
    'get the file path selected by the user
    strPath = Application.FileDialog( _
        msoFileDialogOpen).SelectedItems(1)
End If
End Sub

Result:

Open File Dialog
Step 2:

The function below receives as input a file path and automates that excel workbook:

Private Sub AutomateExcel(ByVal strPath As String)
Dim objExcel As Object
Dim objWorkbook As Object

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.workbooks.Open(strPath)
End Sub

 Step 3: 

The function below receives as input an reference to the excel workbook. It clears all the data in the current word document and it reads the values from the workbook:

Private Sub ReadData(ByRef objWorkbook As Object)
Dim i As Integer

Selection.WholeStory
Selection.Delete Unit:=wdCharacter, Count:=1
For i = 1 To 5
    Selection.TypeText Text:= _
        objWorkbook.sheets(1).Cells(i + 1, 1)
    'move to the next line
    Selection.TypeParagraph
Next i
End Sub

Complete Version:

By putting it all together we end up with the code below:

Option Explicit

Sub Example2()
Dim intChoice As Integer
Dim strPath As String

'only allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
    'get the file path selected by the user
    strPath = Application.FileDialog( _
        msoFileDialogOpen).SelectedItems(1)
    Call AutomateExcel(strPath)
End If
End Sub

Private Sub AutomateExcel(ByVal strPath As String)
Dim objExcel As Object
Dim objWorkbook As Object

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.workbooks.Open(strPath)
Call ReadData(objWorkbook)
End Sub

Private Sub ReadData(ByRef objWorkbook As Object)
Dim i As Integer
Selection.WholeStory
Selection.Delete Unit:=wdCharacter, Count:=1
For i = 1 To 5
    Selection.TypeText Text:= _
        objWorkbook.sheets(1).Cells(i + 1, 1)
    'move to the next line
    Selection.TypeParagraph
Next i
End Sub

Result:

Word Excel, VBA, Result

You can download the file and code related to this article from the links below:

  • Excel to Word.docm
  • Excel to Word.xlsm

See also:

  • Word VBA, Open Document
  • Word Automation VBA, Common Errors
  • Word VBA, Apply Macro to Multiple Files
  • Word VBA, Modify Header For Multiple Files
  • Word Automation VBA, Common Errors
  • VBA, Automating Word From Excel

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

  • Remove From My Forums
  • Question

  • Hi,

    I used

    Cells(i, j).Copy

              
    appWD.Selection.PasteSpecial Placement:=wdInLine, DataType:=wdPasteText

    inside two for-loop to copy a particular cell and paste the cell in word document.

    two problem:

    1. The appWD command paste the cell in the word, but I want the content of the cell to be pasted with plain text?

    2. Sometimes the vba complain about the clipboard object?

    David

    • Changed type

      Thursday, September 11, 2014 1:57 AM
      This is a question

Answers

  • If Not IsEmpty(cell) Then

    • Marked as answer by
      Fei XueMicrosoft employee
      Wednesday, September 17, 2014 9:33 AM

  • In VBE click Tools -> References and add references to Microsoft Word 14.0 Object Library and then 

    Sub Main()
    
        Dim wb As Workbook
        Set wb = ThisWorkbook
        
        Cells(1, 1).Copy
    
        Dim wd As New Word.Application
        wd.Application.Visible = True
        
        Dim wdDoc As Word.Document
        Set wdDoc = wd.Documents.Add
        
        wdDoc.Paragraphs(1).Range.PasteSpecial Placement:=wdInLine, DataType:=wdPasteText
        
    End Sub

    This macro will open Word and paste the text from cell to word as text.

    • Proposed as answer by
      Fei XueMicrosoft employee
      Thursday, September 11, 2014 1:57 AM
    • Marked as answer by
      Fei XueMicrosoft employee
      Wednesday, September 17, 2014 9:33 AM

Понравилась статья? Поделить с друзьями:
  • Excel to vcard converter скачать бесплатно
  • Excel to vcard converter full
  • Excel to vcard converter cracked
  • Excel to the end of a column
  • Excel to text with commas