When dealing with VBA for Excel, you'd be forgiven for thinking that your coding would limit you to working within Excel only. However, if you think carefully about the role of VBA within Office Suite, you'd realize that it is common to all the applications within the suite.
Knowing this, a new set of possibilities opens up. You can, for instance, capture data in Excel via a user form, and then automatically export it to a Word document. The beauty of this is that everything is executed in the background. In other words, you don't need to manually copy data from Excel, search for the correct Word document to paste this information, save the file, and then close Word again.
In this chapter, we will cover the following recipes:
By the end of this chapter, you will be able to create Word documents from within Excel.
This cookbook was written and designed to be used with MS Office 2019 and MS Office 365, installed on either Windows 8, 8.1, or 10.
If your hardware and software meet these requirements, you are good to go.
Demonstration files can be downloaded from https://github.com/PacktPublishing/VBA-Automation-for-Excel-2019-Cookbook.
Please visit the following link to check the CiA videos: https://bit.ly/3jQRvVk.
The first step in the process of creating a Word document from within Excel requires some changes to the available references. To be exact, we'll have to set a reference to Word's object library in the VBA Editor. Without this step, Excel cannot communicate with Word at all, let alone create documents and paragraphs.
In this recipe, we will be creating a new instance of Word from within Excel.
Open Excel, and activate a new workbook. Save the file as a macro-enabled file on your desktop and call it Word_Interaction.xlsm. Sheet1 should be active. Press Alt + F11 to switch to the VBA Editor, and then insert a new module.
It goes without saying that MS Word must also be installed on your computer in order for the instructions in this recipe to work effectively.
Here is how to link Word to Excel:
Note
It is important to know that the reference to the Word object library is only valid for the Excel workbook you're working in currently. Every new workbook will have to be referenced to Word in exactly the same way.
Sub CreateWordDoc()
Dim wdApp As Word.Application
Set wdApp = New Word.Application
wdApp.Visible = True
wdApp.Activate
End Sub
Sub CreateWordDoc()
Dim wdApp As Word.Application
Set wdApp = New Word.Application
With wdApp
.Visible = True
.Activate
.Documents.Add
End With
End Sub
Note
Because we need to use the Word.Application keyword every time we refer to MS Word, the loop structure makes it easier to refer to Word.Application via the wdApp variable.
These steps will enable you to create a new instance of Word from within Excel, using VBA for Excel.
Enabling the Microsoft Word object library for this Excel workbook made it possible to use Word keywords and methods within Excel. These keywords can open an instance of Word, as well as a new Word document, all from within Excel.
It's all very well to know how to open Word with a new document available. However, we need more than this. A heading for the new document would be a good start, but that is still not enough. Formatting the heading is also necessary, and will round it off professionally.
In this recipe, we will be writing and formatting text.
Make sure Word_Interaction.xlsm is still open, and that the VBA Editor is active.
These are the steps to enter and format text in Word:
Sub CreateWordDoc()
Dim wdApp As Word.Application
Set wdApp = New Word.Application
With wdApp
.Visible = True
.Activate
.Documents.Add
.Selection.TypeText "Employee Information"
End With
End Sub
Sub CreateWordDoc()
Dim wdApp As Word.Application
Set wdApp = New Word.Application
With wdApp
.Visible = True
.Activate
.Documents.Add
With .Selection
.ParagraphFormat.Alignment = _
wdAlignParagraphCenter
.BoldRun 'Switch Bold on
.Font.Size = 16
.TypeText "Employee Information"
.BoldRun 'Switch Bold off
.TypeParagraph 'Enter a new line
.Font.Size = 11
.ParagraphFormat.Alignment = _
wdAlignParagraphLeft
.TypeParagraph
End With
End With
End Sub
Using these principles, users will be able to format a Word document with VBA coding in Excel.
We could have opened Word manually and achieved what we've just done, but the whole purpose of the exercise is to do it from Excel, so that data in a spreadsheet can be written to the Word document automatically.
What we need to do now is select data, copy it, and then paste that as part of the opening and formatting process.
In this recipe, we will be copying data into Word.
Make sure that Word_Interaction.xlsm is still open. Activate Sheet1, and enter the following data:
Follow these steps to copy text from Excel to Word:
Sub CreateWordDoc()
Dim wdApp As Word.Application
Set wdApp = New Word.Application
With wdApp
.Visible = True
.Activate
.Documents.Add
With .Selection
.ParagraphFormat.Alignment = _
wdAlignParagraphCenter
.BoldRun 'Switch Bold on
.Font.Size = 16
.TypeText "Employee Information"
.BoldRun 'Switch Bold off
.TypeParagraph 'Enter a new line
.Font.Size = 11
.ParagraphFormat.Alignment = _
wdAlignParagraphLeft
.TypeParagraph
End With
End With
Range("A1", Range("A2").End(xlDown) _
.End(xlToRight)).Copy
wdApp.Selection.Paste
End Sub
Sub CreateWordDoc()
Dim wdApp As Word.Application
Set wdApp = New Word.Application
With wdApp
.Visible = True
.Activate
.Documents.Add
With .Selection
.ParagraphFormat.Alignment = _
wdAlignParagraphCenter
.BoldRun 'Switch Bold on
.Font.Size = 16
.TypeText "Employee Information"
.BoldRun 'Switch Bold off
.TypeParagraph 'Enter a new line
.Font.Size = 11
.ParagraphFormat.Alignment = _
wdAlignParagraphLeft
.TypeParagraph
End With
Range("A1", Range("A2").End(xlDown) _
.End(xlToRight)).Copy
.Selection.Paste
.ActiveDocument.SaveAs2 Environ("UserProfile") _
& "DesktopEmployeeReport.docx"
End With
End Sub
.ActiveDocument.Close
.Quit
'.Visible = True
'.Activate
SaveAsName = Environ("UserProfile") _
& "DesktopEmployeeReport " _
& Format(Now, "yyyy-mm-dd hh-mm-ss") & ".docx"
.ActiveDocument.SaveAs2 SaveAsName
Following these instructions will enable you to automatically copy data from Excel into Word.
Here is an explanation of what we did.
Selecting data in Excel is not a new concept, and neither is copying. Saving it in a Word document with Excel VBA requires making use of the Environ function, as well as formatting of the filename. This will ensure that a new file is created every time the Excel VBA procedure is executed.
Visit https://bettersolutions.com/vba/functions/environ-function.htm for more information on the Environ function and keywords.
To copy an entire Excel spreadsheet and paste it into Word doesn't make sense. You could rather have done everything in Word from the beginning, saving you the whole effort of copying from Excel and pasting in Word.
The point is, if you have an existing Word document or even a Word template, and you regularly need to export selected information from a spreadsheet in Excel to this template, this is the way to do it. The word automation acquires new meaning if you can link Excel with Word in this manner.
In this recipe, we will be pasting Excel data into a Word document at a specific bookmark.
Make sure that Word_Interaction.xlsm is still open, and that the VBA Editor is active.
We need to do the following:
Sub CreateWordDoc()
Dim wdApp As Word.Application
Set wdApp = New Word.Application
With wdApp
.Visible = True
.Activate
.Documents.Add "C:UsersUserDocumentsCustom _
Office TemplatesEmployeeReportTemplate.dotx"
With .Selection
.ParagraphFormat.Alignment = _
wdAlignParagraphCenter
.BoldRun 'Switch Bold on
.Font.Size = 16
.TypeText "Employee Information"
.BoldRun 'Switch Bold off
.TypeParagraph 'Enter a new line
.Font.Size = 11
.ParagraphFormat.Alignment = _
wdAlignParagraphLeft
.TypeParagraph
End With
Sub CreateWordDoc()
Dim wdApp As Word.Application
Dim SaveAsName As String
Set wdApp = New Word.Application
With wdApp
'.Visible = True
'.Activate
.Documents.Add "C:UsersUserDocumentsCustom _
Office TemplatesEmployeeReportTemplate.dotx"
Range("A1", Range("A2").End(xlDown) _
.End(xlToRight)).Copy
.Selection.Goto wdGoToBookmark, , , "ExcelTable"
.Selection.Paste
SaveAsName = Environ("UserProfile") _
& "DesktopEmployeeReport " _
& Format(Now, "yyyy-mm-dd hh-mm-ss") & ".docx"
.ActiveDocument.SaveAs2 SaveAsName
.ActiveDocument.Close
.Quit
End With
End Sub
These instructions will enable you to create a template in Word, and then automatically place content from Excel into the Word document at specific bookmarks.
Inserting Excel data into a Word template can be done with Excel VBA. Inserting a bookmark in the Word template enables Excel to send data to a specific insertion point for the data to be pasted.
Visit https://docs.microsoft.com/en-us/office/vba/api/word.selection.goto for more information on the GoTo method.
18.191.223.123