Moving Excel data fields to Word document - vba

I am trying to make shipping labels for my clients and I need a hand. I have over 500 customers all in an excel file with the usual (Name, Phone #, Address) data fields.
I want to create a VBA that will automatically run a loop to fill my word document with the right data from the Excel file. The word document will be small labels.

It sounds like you need Mail Merge. Check out the links below. That should do what you want.
https://www.ablebits.com/office-addins-blog/2014/05/08/mail-merge-excel-word/
http://www.gcflearnfree.org/print/word2013/mail-merge?playlist=Word_2013
http://www.wa.gov/esd/training/docs/quick_guides/MailMergewithExcelDataFiles.pdf
https://www.youtube.com/watch?v=qiuh7qmA_uc

Related

Word Automation (VBA): Mail Merge Rich Text Format

I'm trying to do a Word MailMerge via VBA from my Access project. I created a clsWordMerge class so I could declare the Word application WithEvents, and take advantage of Word's MailMerge events, mainly the AfterMerge event.
Everything works fine, and I get the finished Word documents created, except that the source fields containing RTF data end up in the document not as formatted text, but instead the RTF codes and data:
<div><font face="Times New Roman" size=3 color=black>This is my <strong><em>test </em></strong>paragraph.</font></div>
Where I would expect to see:
This is my test paragraph
This happens whether I do a mail merge using a CSV file for my data source or an Access table.
So is there any way to correct this, and show the formatted data? I have access to all of the MailMerge events that Word provides.
Thanks..
No, there's no way to merge in RTF and have it display as Word content. RTF is not Word's native file format - a converter is required to display RTF as Word content.
Mail merge literally displays the data text, as it appears in the data source. There are no "advanced features" that enable selectively formatting the mail merge result.
Also, based on painful experience, relying on MailMergeAfterMerge is not advisable. When it was introduced, I tried it, was enthusiastic... until it started failing. The event is unpredictable and not reliable.
Given your requirements, a fully VBA-driven data transfer from Access to Word is a better investment of time and energy.
It probably can be done in certain circumstances, but I agree with Cindy Meister that the Mail Merge Events have not proven reliable (unless they have been fixed - I haven't actually used them for years). The following description of real and likely problems that I have previously encountered when trying this may help:
Not sure any of it can be done if you are merging to Email.
AFAICR the event you are likely to need (MailMergeBeforeRecordMerge) only fires each time Word processes the Main Document, not each time it processes a record in the data source. So if your Mail Merge Main Document "consumes" more than one Data Source record, e.g. because it uses { NEXT } or { NEXTIF } fields, it may be very difficult to get MaiMergeBeforeRecordMerge to do what you need. If I am right about that, that would be enough to put me off making the attempt.
in order to insert your "RTF", you must either
a. Have code that can interpret the "RTF" encoding and do all the right things necessary to insert it in your document, or
b. Have code that saves the "RTF" to an external file, then uses (say) Range.InsertFile to insert it and have Word interpret its contents, or perhaps
c. Use the clipboard to help you do the conversion.
If any of your rich text fields actually contained RTF, (a) would be difficult unless you could find a suitable library to help you. But in fact your sample shows a typical Access rich text field value, which is HTML-like. In fact, I think it is all standard HTML tagging that Word can interpret, but I don't know for sure. That could be much easier to interpret, especially if you only need the plain text (at its simplest, you might be able to throw away the tagging and insert the result.
If your rich text is longer than 255 characters (including the markup), Word's Document.MailMerge.DataSource.DataFields("the case-sensitive field name as Word sees it").Value will be truncated. So if you need the whole of the text or more of it, you'll have to get it somewhere else
The value inserted in the document using a { MERGEFIELD } field is not truncated to 255 characters so you may be able to get the value from the document. Word MailMerge may impose another limit (can't remember, perhaps 64Kb for an OLE DB connection, perhaps less, or perhaps there is a length limit for the data as a whole.
If you can't get the data from the document, you can get it directly from Access. Probably rather easily if your code is running in Access, but it can be done by using ADODB or perhaps ADO from Word VBA code. Your Mail Merge Data Source will need to retrieve the key fields of the record if you want to do that reliably. During development, if your application is running from Access but you are using VBA code in Word, you will probably also need to make sure that you save your Access database each time you modify your Access VBA code, otherwise Access opens the database exclusively and Word won't be able to retrieve data from it.
If you need to use (b) or (c) to save your HTML to a file then you may need to surround the HTML that you get from Access with tags and possibly tags to get Word to recognise the HTML. You could use Scripting.FileSystemObject to save the text, or perhaps ADODB.Stream if you are already using ADODB to retrieve Access data.
You should be able to use VBA Range.InsertFile to insert it, as long as you have some placeholder that tells you what to put it. Or you could use an INCLUDETEXT field and ensure that your Event code updates that field. A snag with the INCLUDETEXT approach is that if you merge to a new document, the INCLUDETEXT fields remain in the document so if you update them, they will all end up with the same result if you do not also create a new file for each source record.
i.e. quite a lot to think about!

How to create a macro in word to import multiple tables from excel?

Frequently in my job I need to generate reports with lots of tables of inputs and results. Especially for the result tables, one change in analysis may require editing a dozen spreadsheets. I'd like to create a macro in word that pulls in data from a spreadsheet, with each table on it's own tab, so that if I update any of those tables in excel the word document tables will also update. Given the number of tables/data points, I don't want to have to tell the macro to pull each single data point. The aim would be to reduce time and errors from manual entry.
I'm thinking this would involve the following steps, but not sure how to go about them:
1) Define the name/size for each table in word with matching name/size in excel
2) Tell the macro to pull the data into a table format
I'm not sure if this is possible as so far I've only seen how to insert a caption or a text box, not insert or update entire tables. Any help would be greatly appreciated!
Depending on what you're doing, you may not even need any VBA code.
If you copy a range from Excel and paste it into Word using Paste Special with the 'paste link' option, any subsequent changes in the Excel range will automatically be reflected in the document when the workbook is saved. And, if you name the range in Excel before copying/pasting, the Word content will expend/contract to reflect changes in the named range's scope in Excel. A variety of paste formats is supported.
Alternatively, you might use a DATABASE field in Word.

How to automatically convert text-based numbers to numbers in several files?

I have 1000 files in Excel format (Excel 2010) and each file contains 7 sheets with data.
This is an example for Excel sheet.
Is there a way to automatically convert the numbers that are stored as text to numbers, without affecting the actual text data? (maybe by VBA macros ? but I am a beginner in VBA code)
I can give you an algorithm, but I don't have time to write the entire code. I would write it in a seperate workbook, for repeatability. You can then either hardcode the 7 file names, or you can make an input for file name (the latter is a bit more flexible, if you need to use it for more files later).
Open a file
Loop all sheets
Loop all cells
If IsNumeric(Cell.Value) > Change format
You should be able to Google your way to the separate parts. Once you have some actual code, you can ask for more help on StackOverflow.

Populate table in Word Template with VBA?

I'm filling in a Word template with data that's been collected from user input. In particular a (variable) number of documents is chosen, and information about each document fills a row of a table.
I've bookmarked several items in the template and successfully filled information in the header from my macro, but the table I'm not so sure with. I bookmarked the first cell and tried tabbing (with Chr(9)) through, and also tried passing an array. (In the template the table has only a first row. Usually tabbing past the last column creates an additional row.)
I can retieve cell contents with
Word.Application.ActiveDocument.Tables(1).Cell(3, 1).Range.Text
but can't write to the any cell except the first, where I placed a bookmark.
Can anyone offer a possible solution to populate the table?
To populate table, use this code
ActiveDocument.Tables(1).Cell(1, 1).Range.Text = "Blah Blah"
This will write to the first cell in the first table. Use a loop to fill the rest of the cells.
I would also recommend see this link.
Topic: Automating Word Tables for Data Insertion and Extraction
Link: http://msdn.microsoft.com/en-us/library/aa537149%28v=office.11%29.aspx#Y1254
Extract:
Summary: Learn how to automate the creation and formatting of tables in Word. Get information about optimizing performance, populating a table with data, formatting table structure, linking table data, and extracting data from a table. (25 printed pages)
I've actually ran into a similar problem using Access to automate filling out a Word table template. I found that if I opened the template in Word prior to running the VBA script, then the Word document is successfully filled out with the table information. My code looks similar to yours as far as adding to it by row. Because the number of fields to be transferred to the form is dynamic it didn't seem like bookmarks for each section would work. If you have any update, I'd be happy to hear of a different way to resolve this.

How to extract specific tables from a MS-Word document using VBA?

VBA is a programming language so I'll assume this question is ok on SO.
What API calls and other techniques can I use, to extract specific tables from an MS-Word document?
I need to write a program which will open several Word documents, and look inside for tables which have a certain text in Row 1 Column 1, and output those tables to another file, preferrably as cells in an Excel spreadsheet.
Is this possible? How would you tackle this? Where to start?
Thanks
The Document.Tables collection contains all tables in a document.
Each Table in this collection has certain properties, such as .Rows, .Columns, or .Cell, which give access to a given row, a given column or a given cell.
The Table.Range.Copy method copies the given table to the clipboard.
The Worksheet.Paste method pastes the copied table into an Excel sheet, using the currently active cell as the insertion point.