Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

How do you write a code that would transfer data from an Excel sheet to a Word document in a specific format?

0

Hi there, 

What I'm trying to achieve is to make shipping labels in Word using the information that's input in Excel. So I had to bookmark the exact positions in a Word template so the Excel data knows where to go but it got too repetitive and the code was not able to run because of it got too big. 

        'Box Number 1    
        wd.Selection.Goto what:=wdGoToBookmark, Name:="number_1"
        wd.Selection.TypeText Text:=sh.Range("A2").Value

        'Quantity 1
        wd.Selection.Goto what:=wdGoToBookmark, Name:="quantity_1"
        wd.Selection.TypeText Text:=sh.Range("B2").Value

        'Factory 1 
        wd.Selection.Goto what:=wdGoToBookmark, Name:="factory_1"
        wd.Selection.TypeText Text:=sh.Range("C2").Value

Because there are 100 items to the code, I had to repeat this code 100 times, so that would be box number 2, quantity 2, factory 2, box number 3, quantity 3, factory 3, so on and so forth until the code got too big. 

In summary, my problem is I know there's a more efficient way to code this without the code becoming too repetitive but I can't figure it out and would really appreciate any help or tip. 

I hope the example I attached makes sense. I'm a complete newbie by the way, so apologies if my explanation is a bit scrambled. 

Answer
Discuss

Answers

0
Selected Answer

Hi Benjamin(?) and welcome to the Forum

Here's a revised answer (for my expediency based your suggestion on the discussion below to have a template with repeated bookmarks for several labels).

You can do this by a loop using your header row A if your Word document  "MarksheetTemplate.docx" has correspondingly named bookmarks (and is stored in the same folder as your workbook - as per your current code). Note that spaces aren't allowed in bookmarks so row A in the attached file now shows headings Box_number, WA_Country, WA_Street and WA_Zip and your Word file will need to have bookmarks matching all the top row values (A to O).

I've added a new variable iCol and instead of using Range("cell name") to refer to individual cells, I've used Cells(<row number>, <column number>) since it's easier to loop using that form e.g. Cells(1, 2) is cell B1.

The key changes from your code (/my previous code) are in bold below. The important bit is the loop section starting For iCol = 1 To 15 where the macro checks that the bookmark (like number_1) exists then adds the value to it from the row in question before deleting the bookmark and moving on. Note that your embedded tempklate has 3 groups of bookmarks so if you add a 4th row in your workbook, the macro will populate the first 3 lables then inform you it can't find the first of the missing 4th bookmarks. I leave you to extend your Word template.

I also used wdDoNotSaveChanges when closing Word (to avoid overwriting the template). It produces a single Word document  (without bookmarks) then alerts the user of the number of labels and file location. Here's the modified code used in the attached workbook, complete with extra comments (generally to right of code) for your guidance:

Sub SendToWord()

'Declare variables for this automation
Dim wd As Word.Application 'Word Application
Dim wDOC As Word.Document ' Word Document
Dim iRow As Long ' Variable to hold the starting row and loop through all records in the table
Dim iCol As Long ' Variable to loop through record columns in the table
Dim sh As Worksheet ' Worksheet variable to refer to the sheet where we have stored the table
Dim TargBook As String ' Variable to hold target bookmark name in Word
Dim DocName As String 'Variable for output Word file and path

Set wd = New Word.Application 'Start word and a new document
Set sh = ThisWorkbook.Sheets("Sheet1") 'set worksheet where table is available

iRow = 2 ' Initialize iRow with 2 as our data is starting from row number 2 from the table

Do While sh.Cells(iRow, 1).Value <> "" ' Do the following while there's something in column "A"

    Set wdDOC = wd.Documents.Open(ThisWorkbook.Path & "\MarksheetTemplate.docx") 'Open the word template
    wd.Visible = False 'without showing on screen

    'Code to insert values from table to a specific bookmark in word application
    On Error Resume Next

    For iCol = 1 To 15 'from column A to O...
        TargBook = sh.Cells(1, iCol).Value & "_" & iRow - 1 'create target bookmark name
        If wdDOC.Bookmarks.Exists(TargBook) = True Then  'check header bookmark exists then...
            wd.Selection.Goto what:=wdGoToBookmark, Name:=TargBook
            wd.Selection.TypeText Text:=sh.Cells(iRow, iCol).Value 'take column value from loop row
            wdDOC.Bookmarks(TargBook).Delete ' delete bookmark
        Else
            n = MsgBox("Please check template; cannot find Word bookmark: " & TargBook, vbOKOnly) ' Tell user something's missing
            Exit Do 'then stop populating Word document
        End If
    Next iCol

    iRow = iRow + 1

Loop

If sh.Cells(1, 17).Value = "" Then sh.Cells(1, 17).Value = "MyLabels" 'give filename if Q1 is empty
DocName = ThisWorkbook.Path & "\" & sh.Cells(1, 17).Value & ".docx" 'combine path and document name
wdDOC.SaveAs (DocName) 'Close the word file
wdDOC.Close (wdDoNotSaveChanges) ' don't overwrite template
Set wdDOC = Nothing 'Release the memory of wddoc
wd.Quit 'Close MS Word Application
Set wd = Nothing 'Release the memory allocated to WD variable

n = MsgBox((iRow - 2) & " Labels have been created successfully in file " & DocName, vbOKOnly) ' Tell the user how many labels were made

End Sub

Other users should note that the code relies on the Microsoft Word 16.0 Object library (or other version) being installed already (via VB Editor/Tool/References).

You could/should make further improvements like checking if the output document already exists (if you don't want to overwrite it) but I hope this works for you.

Discuss

Discussion

@John, Don says it's "working exactly as it's supposed to" but if you want to prevent the site's HTML from inserting a blank line for every CR you should add the CODE tags first and paste your code between them. The blank lines are inserted when you paste the code first, select and paste the tags.
Variatus (rep: 4889) Jun 21, '21 at 8:09 pm
Hi John, thanks for answering my question!

I'm a bit confused though, it runs perfectly but I can't seem to find the word file created afterward. 
SoupierAuthor (rep: 4) Jun 22, '21 at 12:18 am
@Variatus. Thanks but I always add the CODE first. Extra CRs have confused me from the start!

@Benjamin. You need to have the named template document with the correct bookmarks in the same folder as the workbook AND a file name per row in column 17 (since the file name can't be "") . The files will be in that folder.
John_Ru (rep: 6142) Jun 22, '21 at 1:23 am
I see, thank you! 

Another question, can this code be adjusted so that it works per label? 

So imagine this is the Word template: 

Box number: 
Factory: 
Quantity: 

Box number: 
Factory: 
Quantity: 

Box number: 
Factory: 
Quantity: 

If I understand it correctly, the code checks for the column header and matches it to the appropriate bookmark right? So data under Box_number header in Excel would be transferred to Box_number bookmark in Word. But is it possible that the data on (1, iCol) is for Box_number_1, Factory_1, Quantity_1, and then the data on (2, iCol) is for Box_number_2, Factory_2, Quantity_2 etc and be all on the same file? 
SoupierAuthor (rep: 4) Jun 22, '21 at 1:49 am
Benjamin.

Firstly, I may have misunderstood your question since my Answer macro produces a named Word document per row (I imagined you were producing large shipping labels, for crates say). I now think you want a single document including x labels.

The code could be changed to populate bookmarks like Box_number_1 but you'd need to produce a Word template with say 20 groups of bookmarks.

Another approach would be to create temp files then append new pages or paragraphs to a single output document. Depends what your Word file looks like (e.g. is it a Avery Labels tempate or similar).

If you have that Word document, please embed it in your Excel file (if you're not sure how, follow the Microfsoft guidance here:Insert an object in your Excel spreadsheet). Then edit your orginal question to embed that revised file using (Remove then) Add files. Lewt me know and I'll see what I can do later.
John_Ru (rep: 6142) Jun 22, '21 at 2:52 am
@John Hi John, thanks for responding. Yes, apologies, I wasn't able to explain it clearly (English isn't really my first language) but that's what I was hoping to achieve - have the small labels (around 100 of them) in one file. So in the file that I uploaded, there are three bookmarks for each column, number_1, number_2, number_3 then quantity_1, quantity_2, quantity_3 and so on. 
SoupierAuthor (rep: 4) Jun 22, '21 at 3:11 am
Benjamin, your language was fine but I misunderstood!

Thanks for the revised file but that didn't include the Word file itself- please try again but use the "Display as icon" option when inserting the Word file. It won't show the document design in Excel but I'll be able to save the file (from the icon) and work with it.
John_Ru (rep: 6142) Jun 22, '21 at 3:18 am
Thanks John, I revised it again. 
SoupierAuthor (rep: 4) Jun 22, '21 at 3:23 am
See revised Answer please
John_Ru (rep: 6142) Jun 22, '21 at 5:06 am
@John damn, it worked perfectly. You're a massive help sir, thank you so much! 
SoupierAuthor (rep: 4) Jun 22, '21 at 5:33 am
Glad it did! Have fun.
John_Ru (rep: 6142) Jun 22, '21 at 5:38 am
@John by the way, just another question. Is it possible to also transfer an image from a cell in Excel to Word along with the other data? It seems confusing to me because whenever I insert an image in a cell, it's as if the image is actually just floating above the cell and not actually in it. Is there a code that can read that and transfer it to the word document too? 
SoupierAuthor (rep: 4) Jun 22, '21 at 6:52 am
Benjamin. You're right- that's another question (different topic) so please create a new, separate question on the Forum (with a suitable title and sufficient detail/ example Excel file) and one of us will answer.
John_Ru (rep: 6142) Jun 22, '21 at 8:45 am
@John, right. Thanks again John, really appreciate your help. 
SoupierAuthor (rep: 4) Jun 23, '21 at 12:03 am
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login