Solved

Programming Database utilizing Mail Merge in Microsoft Word...

Posted on 2002-06-06
6
294 Views
Last Modified: 2010-04-04
       Suppose I want to write 100 Letter to which people I've already had their names in MDB Database... Here's what I want them see in their letter...

  "Hello,[Name of my people in MDB Database], I'm using Mail Merge with Delphi"

        Because of a goverment restriction to applicaion forms, Microsoft Word seems to be the best Application to generate such a letter.
        You all please show me some code that capable of interfacing to Word Mail Merge using Text Shown above..., Complete code would have my points and it's a urgently required...
0
Comment
Question by:DOOM_DAEMON
  • 3
  • 2
6 Comments
 
LVL 14

Accepted Solution

by:
DragonSlayer earned 250 total points
ID: 7060855
Here's some code snippets that I have (originally not mine, though)


unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure InsertLines(LineNum : Integer);
    procedure CreateMailMergeDataFile;
    procedure FillRow(Doc : Variant; Row : Integer;
                 Text1,Text2,Text3,Text4 : String);
  private
    { Private declarations }

  public
    wrdApp, wrdDoc: Variant;
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses ComObj;

Const wdAlignParagraphLeft = 0;
Const wdAlignParagraphCenter = 1;
Const wdAlignParagraphRight = 2;
Const wdAlignParagraphJustify = 3;
Const wdAdjustNone = 0;
Const wdGray25 = 16;
Const wdGoToLine = 3;
Const wdGoToLast = -1;
Const wdSendToNewDocument = 0;

{$R *.DFM}

procedure TForm1.InsertLines(LineNum : Integer);
var
  iCount : Integer;
begin
  for iCount := 1 to LineNum do
     wrdApp.Selection.TypeParagraph;
end;

procedure TForm1.FillRow(Doc : Variant; Row : Integer;
                 Text1,Text2,Text3,Text4 : String);

begin
  Doc.Tables.Item(1).Cell(Row,1).Range.InsertAfter(Text1);
  Doc.Tables.Item(1).Cell(Row,2).Range.InsertAfter(Text2);
  Doc.Tables.Item(1).Cell(Row,3).Range.InsertAfter(Text3);
  Doc.Tables.Item(1).Cell(Row,4).Range.InsertAfter(Text4);
end;

procedure TForm1.CreateMailMergeDataFile;
var
  wrdDataDoc : Variant;
  iCount : Integer;
begin
  // Create a data source at C:\DataDoc.doc containing the field data
  wrdDoc.MailMerge.CreateDataSource('C:\DataDoc.doc',,,'FirstName, LastName,' +
       ' Address, CityStateZip');
  // Open the file to insert data
  wrdDataDoc := wrdApp.Documents.Open('C:\DataDoc.doc');
  for iCount := 1 to 2 do
    wrdDataDoc.Tables.Item(1).Rows.Add;
  // Fill in the data
  FillRow(wrdDataDoc, 2, 'Steve', 'DeBroux',
        '4567 Main Street', 'Buffalo, NY  98052');
  FillRow(wrdDataDoc, 3, 'Jan', 'Miksovsky',
        '1234 5th Street', 'Charlotte, NC  98765');
  FillRow(wrdDataDoc, 4, 'Brian', 'Valentine',
        '12348 78th Street  Apt. 214', 'Lubbock, TX  25874');
  // Save and close the file
  wrdDataDoc.Save;
  wrdDataDoc.Close(False);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  StrToAdd : String;
  wrdSelection, wrdMailMerge, wrdMergeFields : Variant;
begin
  // Create an instance of Word and make it visible
  wrdApp := CreateOleObject('Word.Application');
  wrdApp.Visible := True;
  // Create a new document
  wrdDoc := wrdApp.Documents.Add();
  wrdDoc.Select;

  wrdSelection := wrdApp.Selection;
  wrdMailMerge := wrdDoc.MailMerge;

  // Create MailMerge data file
  CreateMailMergeDataFile;


  // Create a string and insert it into the document
  StrToAdd := 'State University' + Chr(13) +
              'Electrical Engineering Department';
  wrdSelection.ParagraphFormat.Alignment := wdAlignParagraphCenter;
  wrdSelection.TypeText(StrToAdd);

  InsertLines(4);

  // Insert Merge Data
  wrdSelection.ParagraphFormat.Alignment := wdAlignParagraphLeft;
  wrdMergeFields := wrdMailMerge.Fields;

  wrdMergeFields.Add(wrdSelection.Range,'FirstName');
  wrdSelection.TypeText(' ');
  wrdMergeFields.Add(wrdSelection.Range,'LastName');
  wrdSelection.TypeParagraph;
  wrdMergeFields.Add(wrdSelection.Range,'Address');
  wrdSelection.TypeParagraph;
  wrdMergeFields.Add(wrdSelection.Range,'CityStateZip');

  InsertLines(2);

  // Right justify the line and insert a date field with
  // the current date
  wrdSelection.ParagraphFormat.Alignment := wdAlignParagraphRight;
  wrdSelection.InsertDateTime('dddd, MMMM dd, yyyy',False);

  InsertLines(2);

  // Justify the rest of the document
  wrdSelection.ParagraphFormat.Alignment := wdAlignParagraphJustify;

  wrdSelection.TypeText('Dear ');
  wrdMergeFields.Add(wrdSelection.Range,'FirstName');

  wrdSelection.TypeText(',');
  InsertLines(2);

  // Create a string and insert it into the document
  StrToAdd := 'Thank you for your recent request for next ' +
      'semester''s class schedule for the Electrical ' +
      'Engineering Department.  Enclosed with this ' +
      'letter is a booklet containing all the classes ' +
      'offered next semester at State University.  ' +
      'Several new classes will be offered in the ' +
      'Electrical Engineering Department next semester.  ' +
      'These classes are listed below.';
  wrdSelection.TypeText(StrToAdd);

  InsertLines(2);

  // Insert a new table with 9 rows and 4 columns
  wrdDoc.Tables.Add(wrdSelection.Range,9,4);
  wrdDoc.Tables.Item(1).Columns.Item(1).SetWidth(51,wdAdjustNone);
  wrdDoc.Tables.Item(1).Columns.Item(2).SetWidth(170,wdAdjustNone);
  wrdDoc.Tables.Item(1).Columns.Item(3).SetWidth(100,wdAdjustNone);
  wrdDoc.Tables.Item(1).Columns.Item(4).SetWidth(111,wdAdjustNone);
  // Set the shading on the first row to light gray

  wrdDoc.Tables.Item(1).Rows.Item(1).Cells
      .Shading.BackgroundPatternColorIndex := wdGray25;
  // BOLD the first row
  wrdDoc.Tables.Item(1).Rows.Item(1).Range.Bold := True;
  // Center the text in Cell (1,1)
  wrdDoc.Tables.Item(1).Cell(1,1).Range.Paragraphs.Alignment :=
        wdAlignParagraphCenter;

  // Fill each row of the table with data
  FillRow(wrdDoc, 1, 'Class Number', 'Class Name', 'Class Time',
     'Instructor');
  FillRow(wrdDoc, 2, 'EE220', 'Introduction to Electronics II',
     '1:00-2:00 M,W,F', 'Dr. Jensen');
  FillRow(wrdDoc, 3, 'EE230', 'Electromagnetic Field Theory I',
     '10:00-11:30 T,T', 'Dr. Crump');
  FillRow(wrdDoc, 4, 'EE300', 'Feedback Control Systems',
     '9:00-10:00 M,W,F', 'Dr. Murdy');
  FillRow(wrdDoc, 5, 'EE325', 'Advanced Digital Design',
     '9:00-10:30 T,T', 'Dr. Alley');
  FillRow(wrdDoc, 6, 'EE350', 'Advanced Communication Systems',
     '9:00-10:30 T,T', 'Dr. Taylor');
  FillRow(wrdDoc, 7, 'EE400', 'Advanced Microwave Theory',
     '1:00-2:30 T,T', 'Dr. Lee');
  FillRow(wrdDoc, 8, 'EE450', 'Plasma Theory',
     '1:00-2:00 M,W,F', 'Dr. Davis');
  FillRow(wrdDoc, 9, 'EE500', 'Principles of VLSI Design',
     '3:00-4:00 M,W,F', 'Dr. Ellison');

  // Go to the end of the document

  wrdApp.Selection.GoTo(wdGotoLine,wdGoToLast);
  InsertLines(2);

  // Create a string and insert it into the document
  StrToAdd := 'For additional information regarding the ' +
             'Department of Electrical Engineering, ' +
             'you can visit our website at ';
  wrdSelection.TypeText(StrToAdd);
  // Insert a hyperlink to the web page
  wrdSelection.Hyperlinks.Add(wrdSelection.Range,'http://www.ee.stateu.tld');
  // Create a string and insert it into the document
  StrToAdd := '.  Thank you for your interest in the classes ' +
             'offered in the Department of Electrical ' +
             'Engineering.  If you have any other questions, ' +
             'please feel free to give us a call at ' +
             '555-1212.' + Chr(13) + Chr(13) +
             'Sincerely,' + Chr(13) + Chr(13) +
             'Kathryn M. Hinsch' + Chr(13) +
             'Department of Electrical Engineering' + Chr(13);
  wrdSelection.TypeText(StrToAdd);

  // Perform mail merge
  wrdMailMerge.Destination := wdSendToNewDocument;
  wrdMailMerge.Execute(False);

  // Close the original form document
  wrdDoc.Saved := True;
  wrdDoc.Close(False);

  // Notify the user we are done.
  ShowMessage('Mail Merge Complete.');

  // Clean up temp file
  DeleteFile('C:\DataDoc.doc');

end;

end.



HTH
DragonSlayer
0
 
LVL 1

Author Comment

by:DOOM_DAEMON
ID: 7061953
DragonSlayer, You know what? You're something else! What a great example you've... I've test it and it's work. Anyway, I have two more questions and I'll give you my points
    1. Would you please show me some codes in order to have this report printed out to printer.
    2. Suppose that I have my mail merge doc and a certain field name in this mail merge say "Name"  and such doc contain informations already prepared to suite government application I must do. How can I replace a database field to that forms
    Whether you answer this two more questions I've post today or not? I'll give me my points as I promise but please let me know if you don't want to? Please...
0
 
LVL 4

Expert Comment

by:jsweby
ID: 7062283
If you have a text file datasource then the best thing is to have the first record as field names that match the mail merge field names. Word will then automatically assign the correct fields in your data source to the corresponding fields in the mailmerge document.

As for printing, put Printers in your uses clause, drop a PrintDialog on your form and use the following code:

If (PrintDialog1.Execute) then
begin
     wrdApp.ActivePrinter := Printer.Printers[Printer.PrinterIndex];
     wrdDoc.PrintOut(False); {Parameter is whether to background print or not}
end;

J.
0
ScreenConnect 6.0 Free Trial

At ScreenConnect, partner feedback doesn't fall on deaf ears. We collected partner suggestions off of their virtual wish list and transformed them into one game-changing release: ScreenConnect 6.0. Explore all of the extras and enhancements for yourself!

 
LVL 1

Author Comment

by:DOOM_DAEMON
ID: 7063967
    Thanks for your comments ,jsweby. But problems I've found is that word document that is written to be master form of mail merge contains location of files to be datasources. Can I write some code to change it's datasource file name in order to place this docs in different location depends on what location user want and I'm responsible for make it work properly...
0
 
LVL 1

Author Comment

by:DOOM_DAEMON
ID: 7065566
     Well done, DragonSlay. You help me out my lousy problems and make my Delphi Programming Technique Improved. Here's some gift for your, Experts. Thanks you very much.
0
 
LVL 14

Expert Comment

by:DragonSlayer
ID: 7066143
I'm very soory DOOM_DAEMON, I was away for a few days (holiday!) and didn't check my mail... so sorry for not answering the other Questions.
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Objective: - This article will help user in how to convert their numeric value become words. How to use 1. You can copy this code in your Unit as function 2. than you can perform your function by type this code The Code   (CODE) The Im…
Introduction The parallel port is a very commonly known port, it was widely used to connect a printer to the PC, if you look at the back of your computer, for those who don't have newer computers, there will be a port with 25 pins and a small print…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question