Excel to doc 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.

Sub ExcelRangeToWord()

‘PURPOSE: Copy/Paste An Excel Table Into a New Word Document
‘NOTE: Must have Word Object Library Active in Order to Run _
  (VBE > Tools > References > Microsoft Word 12.0 Object Library)

‘SOURCE: www.TheSpreadsheetGuru.com

Dim tbl As Excel.Range
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table

‘Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False

‘Copy Range from Excel
  Set tbl = ThisWorkbook.Worksheets(Sheet1.Name).ListObjects(«Table1»).Range

‘Create an Instance of MS Word
  On Error Resume Next

        ‘Is MS Word already opened?
      Set WordApp = GetObject(class:=»Word.Application»)

        ‘Clear the error between errors
      Err.Clear

    ‘If MS Word is not already open then open MS Word
      If WordApp Is Nothing Then Set WordApp = CreateObject(class:=»Word.Application»)

        ‘Handle if the Word Application is not found
      If Err.Number = 429 Then
        MsgBox «Microsoft Word could not be found, aborting.»
        GoTo EndRoutine
      End If

  On Error GoTo 0

  ‘Make MS Word Visible and Active
  WordApp.Visible = True
  WordApp.Activate

    ‘Create a New Document
  Set myDoc = WordApp.Documents.Add

  ‘Copy Excel Table Range
  tbl.Copy

‘Paste Table into MS Word
  myDoc.Paragraphs(1).Range.PasteExcelTable _
    LinkedToExcel:=False, _
    WordFormatting:=False, _
    RTF:=False

‘Autofit Table so it fits inside Word Document
  Set WordTable = myDoc.Tables(1)
  WordTable.AutoFitBehavior (wdAutoFitWindow)

   EndRoutine:
‘Optimize Code
  Application.ScreenUpdating = True
  Application.EnableEvents = True

‘Clear The Clipboard
  Application.CutCopyMode = False

End Sub

In this part of the code we are determining if Microsoft Word is open or not.  If Word is already open, we can set a variable equal to the entire program by using GetObject.  If MS Word is not currently running we can use CreateObject to run an instance of Word and then set a variable equal to that specific instance of MS Word.

When using CreateObject, the target application will start running but it is not visible on screen.  Therefore we need to turn the Visible setting on (equal to true).  Also, VBA with Word is a little bit different than with Excel in that it is much more dependent on its window showing on screen.  Therefore a second command must be written to Activate Microsoft Word.

Copy From Excel, Paste Onto Document

Now that you have a new document created, you can command Excel to paste your table into MS Word.  Near the beginning of the code, there was a line that allowed you to specify the exact table you wanted to copy.  The variable tbl was used to remember this table range and to allow you to reference the range later on in the code.  

Guru Tip: It is a good idea to place code that may need to be manually changed at some point in the future near the beginning of the subroutine.  This prevents you from having to scroll through your code and pinpoint the exact place where you spelled out which range you wanted to copy or which worksheet you wanted to pull data from.  This can save you a bunch of time and prevent confusion!

Word has a special method called PasteExcelTable, which (as you can guess) allows you paste in an Excel table.  There are three variables you can tweak to get you table looking and functioning just the way you want.

  • LinkedToExcel True links the pasted table to the original Excel file so that changes made to the Excel file are reflected in Microsoft Word.

  • WordFormatting True formats the table using the formatting in the Word document.  False formats the table according to the original Excel file.

  • RTF True pastes the Excel table using Rich Text Format (RTF).  False pastes the Excel table as HTML.

Now for the last step!  Depending on how large your table is, it may be spilling outside of your document page.  In order to prevent this from happening you can go ahead and use AutoFitBehavior to resize the table to fit perfectly inside your Word document.

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon!

— Chris
Founder, TheSpreadsheetGuru.com

Содержание

  1. How to Open a Word Document from Excel and Copy Excel Data to the Word Document using VBA
  2. Tools you can use
  3. Create and Open a New Word Document using Macro
  4. Copy Excel Data into a Newly Created Word Document
  5. Excel VBA export Excel to Word
  6. Excel VBA export Excel to Word
  7. Excel VBA export Excel to Word (Single Worksheet)
  8. Excel VBA export Excel to Word (Multiple Worksheets)
  9. An Excel Blog For The Real World
  10. VBA To Copy/Paste Excel Table Into Microsoft Word
  11. Moving An Excel Table Into A New Word Document
  12. Teaching Excel The MS Word Language
  13. Opening MS Word From Inside Excel
  14. Controlling MS Word From Inside Excel
  15. Copy From Excel, Paste Onto Document
  16. Some Snippets For Possible Code Modifications
  17. How Can You Use These Concepts?
  18. Download Example Excel File
  19. About The Author
  20. How to Copy Data From Excel to Word Using VBA Excel
  21. The Process Of Copying Excel Data To A Word File Using Excel VBA
  22. Example : Paste Excel Data To Word Using VBA

How to Open a Word Document from Excel and Copy Excel Data to the Word Document using VBA

Tools you can use

Create and Open a New Word Document using Macro

First, let’s create a new word document using a Macro. We can use the CreateObject() method in VBA to create a new instance of a Word document.

In the above example, I am just creating new instance of a Word document and making it visible, that is, it will open the word file (or document).

Now, we need to add a blank document to the word file. This is where you write your stuff, add table etc.

Activating the document, will set focus on the word file. You can skip the .Activate part, Excel will simply create a word file, and you can see the file in your task bar .

So, now you know how to create a new Word document from Excel using VBA. It’s a simple method. Let’s write the entire code in a procedure.

You can call the above procedure from a button click event, or execute the code when your workbook loads .

Copy Excel Data into a Newly Created Word Document

Now the real code. Did you see the first image in this post? It shows what I am going to do here in this example.

I have range of data in Excel, a table with few columns and rows. I also have a button (an ActiveX control). I wish to create a new word file from my VBA macro and copy the Excel data in the Word file (or document).

I want the data in table format in my word document. Its a very interesting example. You should.

First, create a range of data in Excel. You and add or remove columns or rows from the range. Since, in the example, I am using the UsedRange property to extract data from the worksheet.

Источник

Excel VBA export Excel to Word

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

You may also want to read:

Excel VBA export Excel to Word

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

For example, we have the below worksheet

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.

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.

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

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.

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.

Источник

An Excel Blog For The Real World

A blog focused primarily on Microsoft Excel, PowerPoint, & Word with articles aimed to take your data analysis and spreadsheet skills to the next level. Learn anything from creating dashboards to automating tasks with VBA code!

VBA To Copy/Paste Excel Table Into Microsoft Word

Moving An Excel Table Into A New Word Document

In this post you will learn how to write VBA code to automate copy and pasting an Excel table range into a new Word document. The article should provide a good foundation to allow you to create a personalized VBA macro that suites your specific task needs. Maybe you need to copy over an Excel range or paste your table after paragraph 3 in a Word document. With minor tweaks to the following code you should be able to accomplish all of this with a little further research (aka ‘googling’). Below is the macro code you can insert into an Excel VBA module and run. Right below the VBA code I will provide a little more detail on what the macro routine is doing so you can fully understand its makeup.

‘PURPOSE: Copy/Paste An Excel Table Into a New Word Document
‘NOTE: Must have Word Object Library Active in Order to Run _
(VBE > Tools > References > Microsoft Word 12.0 Object Library)
‘SOURCE: www.TheSpreadsheetGuru.com

Dim tbl As Excel.Range
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table

‘Optimize Code
Application.ScreenUpdating = False
Application.EnableEvents = False

‘Copy Range from Excel
Set tbl = ThisWorkbook.Worksheets(Sheet1.Name).ListObjects(«Table1»).Range

‘Create an Instance of MS Word
On Error Resume Next

‘Is MS Word already opened?
Set WordApp = GetObject(class:=»Word.Application»)

‘Clear the error between errors
Err.Clear

‘If MS Word is not already open then open MS Word
If WordApp Is Nothing Then Set WordApp = CreateObject(class:=»Word.Application»)

‘Handle if the Word Application is not found
If Err.Number = 429 Then
MsgBox «Microsoft Word could not be found, aborting.»
GoTo EndRoutine
End If

On Error GoTo 0

‘Make MS Word Visible and Active
WordApp.Visible = True
WordApp.Activate

‘Create a New Document
Set myDoc = WordApp.Documents.Add

‘Copy Excel Table Range
tbl.Copy

‘Paste Table into MS Word
myDoc.Paragraphs(1).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:= False , _
RTF:= False

‘Autofit Table so it fits inside Word Document
Set WordTable = myDoc.Tables(1)
WordTable.AutoFitBehavior (wdAutoFitWindow)

End Routine:
‘Optimize Code
Application.ScreenUpdating = True
Application.EnableEvents = True

‘Clear The Clipboard
Application.CutCopyMode = False

Teaching Excel The MS Word Language

In order to control Microsoft Word from inside Excel’s Visual Basic Editor, we need to teach Excel how to speak in Word’s own terminology. MS Word uses a vocabulary containing terms such as «Document» and «Paragraph» that simply do not exist in Excel’s own code language. You can learn more about this topic by reading my post Teaching Excel To Speak PowerPoint. In order to activate MS Word’s object library, simply click the Tools menu in the Visual Basic Editor and select Reference. Then make sure the reference Microsoft Office Word 12.0 Object Library is checked. In the below image I show you exactly how to do this!

Opening MS Word From Inside Excel

Now that we have taught Excel how to communicate with Microsoft Word, let’s look at how we can accomplish pasting an Excel table into a brand new Word document. Near the beginning of the code there is a section that looks like this:

‘Create an Instance of MS Word
On Error Resume Next

‘Is MS Word already opened?
Set WordApp = GetObject(class:=»Word.Application»)

‘Clear the error between errors
Err.Clear

‘If MS Word is not already open then open MS Word
If WordApp Is Nothing Then Set WordApp = CreateObject(class:=»Word.Application»)

‘Handle if the Word Application is not found
If Err.Number = 429 Then
MsgBox «Microsoft Word could not be found, aborting.»
GoTo EndRoutine
End If

On Error GoTo 0

In this part of the code we are determining if Microsoft Word is open or not. If Word is already open, we can set a variable equal to the entire program by using GetObject. If MS Word is not currently running we can use CreateObject to run an instance of Word and then set a variable equal to that specific instance of MS Word.

When using CreateObject, the target application will start running but it is not visible on screen. Therefore we need to turn the Visible setting on (equal to true). Also, VBA with Word is a little bit different than with Excel in that it is much more dependent on its window showing on screen. Therefore a second command must be written to Activate Microsoft Word.

‘Make MS Word Visible and Active
WordApp.Visible = True
WordApp.Activate

Controlling MS Word From Inside Excel

Now that you are 100% sure Word is running, you can begin to control it! Let’s first command Word to make a brand new document to paste your table to. Along the way it is important to set a variable during each stage of creation so that if you ever want to reference the document later on you can do so with your respective variable.

‘Create a New Document
Set myDoc = WordApp.Documents.Add

Copy From Excel, Paste Onto Document

Now that you have a new document created, you can command Excel to paste your table into MS Word. Near the beginning of the code, there was a line that allowed you to specify the exact table you wanted to copy. The variable tbl was used to remember this table range and to allow you to reference the range later on in the code.

Guru Tip: It is a good idea to place code that may need to be manually changed at some point in the future near the beginning of the subroutine. This prevents you from having to scroll through your code and pinpoint the exact place where you spelled out which range you wanted to copy or which worksheet you wanted to pull data from. This can save you a bunch of time and prevent confusion!

Word has a special method called PasteExcelTable, which (as you can guess) allows you paste in an Excel table. There are three variables you can tweak to get you table looking and functioning just the way you want.

LinkedToExcelTrue links the pasted table to the original Excel file so that changes made to the Excel file are reflected in Microsoft Word.

WordFormattingTrue formats the table using the formatting in the Word document. False formats the table according to the original Excel file.

RTFTrue pastes the Excel table using Rich Text Format (RTF). False pastes the Excel table as HTML.

Now for the last step! Depending on how large your table is, it may be spilling outside of your document page. In order to prevent this from happening you can go ahead and use AutoFitBehavior to resize the table to fit perfectly inside your Word document.

‘Copy Excel Table Range
tbl.Copy

‘Paste Table into MS Word
myDoc.Paragraphs(1).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:= False , _
RTF:=False

‘Autofit Table so it fits inside Word Document
Set WordTable = myDoc.Tables(1)
WordTable.AutoFitBehavior (wdAutoFitWindow)

Some Snippets For Possible Code Modifications

Robert K asks, «What if I want I want my macro to copy the table to a specific Word Document?»

‘Change: [Set myDoc = WordApp.Documents.Add] to:
Set myDoc = WordApp.Documents.Open(«C:UserschrisDesktopDocument Name.docx»)

David C asks, «How do I paste the table into a specific line on the Word Document?»

‘Change: [myDoc.Paragraphs(1).Range.PasteExcelTable _] to:
myDoc.Paragraphs(6).Range.PasteExcelTable _

How Can You Use These Concepts?

I want to hear from you and learn how you might use this VBA code in your workflow. Also, what types of modifications would you make to fit your needs? I look forward to reading your thoughts in the comment section below!

Download Example Excel File

If you would like to get a copy of the Excel file I used throughout this article, feel free to directly download the spreadsheet by clicking the download button below.

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon!

Источник

How to Copy Data From Excel to Word Using VBA Excel

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

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

‘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

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

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

‘saving the document

‘closing the document

‘Emptying the Clipboard

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.

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.

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.

Источник

Понравилась статья? Поделить с друзьями:
  • Excel to do list sample
  • Excel to dbf vba
  • Excel to dbf online
  • Excel to csv с изображениями
  • Excel to csv двойные кавычки