Using vba to automate a Microsoft Word document wi

2019-09-18 08:08发布

问题:

I'm trying to populate a Word document with information from Excel. The table on excel looks really simple.

  QUESTION              |YES|  DATA

 Prewritten question 1  | X | Prewritten data 1

 Prewritten question 2  | X | Prewritten data 2

 Prewritten question 3  | X | Prewritten data 3

How would I then automate populating a new word document with the data with the variable X under YES, only pasting the prewritten data held in the data column?

I almost got this working on Word just using the step by step mail merger feature , but while I was able to populate the Word document, the Prewritten data would paste, but each pasted selection from the data column would take its own page on Word, even if it was a short 3 word phrase.

回答1:

The simplest way for you would be without code, using a Word field.

  1. In Excel, select the range of data and assign it a name (Range name)
  2. In Word Insert/Text/Quick Parts/Field
  3. from the list, choose Database. An Insert Database button will appear, click that.
  4. In the dialog box, Step 1, navigate to the location of the Workbook and select it. You'll be prompted for the connection protocol (OLEDB is fine). Select the Range Name from the list.
  5. Choose "Query Options" in Step 2. Tab "Select Fields": In the list on the right, select the fields you do NOT want and click "Remove". Tab "Filter Records": Choose the "Yes" column and set Comparison "Equal to" and type X in the third box.
  6. In Step 3 click "Insert Data"; be sure to activate "Insert Data as Field" checkbox to get an active link back to the Workbook.

This will insert a Database field in the Word document with syntax something like the following. Press Alt+F9 to toggle between field result and field display views. If you've done any work with data connections some of it will look familiar to you. In any case, you should recognize the file path near the beginning and the SQL select statement at the end.

{ DATABASE  \d "C:\\Test\\ExcelDataRange.xlsx" 
  \c "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;
  Data Source=C:\\Test\\ExcelDataRange.xlsx;Mode=Read;
  Extended Properties=\"HDR=YES;IMEX=1;\";
  Jet OLEDB:System database=\"\";Jet OLEDB:Registry Path=\"\";
  Jet OLEDB:Engine Type=35;Jet OLEDB:Database Locking Mode=0;
  Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;
  Jet OLEDB:New Database Password=\"\";Jet OLEDB:Create System Database=False;
  Jet OLEDB:Encrypt Database=False;
  Jet OLEDB:Don't Copy Locale on Compact=False;
  Jet OLEDB:Compact Without Replica Repair=False;
  Jet OLEDB:SFP=False;Jet OLEDB:Support Complex Data=False;
  Jet OLEDB:Bypass UserInfo Validation=False" 
  \s "SELECT `Data` FROM `Test` WHERE ((`Yes` = 'X'))" }

If the data in the workbook changes, click in the table and press F9 to update the field. (If you add rows to the range be sure to adjust the Range Name to include them all!)