Search code examples
delphims-wordoutlookmailmerge

Inputting data from a dbgrid into a word mail merge


I'm wanting to create a mail marge for a letter inputting different names and address on each. I've used Microsoft example as a base point http://support.microsoft.com/kb/229310 and i've customized it to how i like. But my problem arises when trying to get the data for either selected rows of the dbgrid or just the whole thing. I have no idea how to do it. My first thought was do 1 to the amount of rows, then put some tedit boxes down and put them equal to mailmerged data but that still only does it one at a time. The dbgrid is linked up to a ms outlook. This is how they fill the data..

// Open the file to insert data
wrdDataDoc := wrdApp.Documents.Open('E:\Temp.doc');
 for iCount := 1 to (DBGrid1.DataSource.DataSet.RecordCount) do
wrdDataDoc.Tables.Item(1).Rows.Add;
FillRow(wrdDataDoc, 2, 'Steve', 'DeBroux',
    '4567 Main Street', 'Buffalo, NY  98052');
// Fill in the data
FillRow(wrdDataDoc, 3, 'Jan', 'Miksovsky',
    '1234 5th Street', 'Charlotte, NC  98765');
FillRow(wrdDataDoc, 4, 'Brian', 'Valentine',
    '12348 78th Street  Apt. 214', 'Lubbock, TX  25874');

So how would I grab the data from the dbgrid and fill the file with that information?


Solution

  • var
      i: Integer;
      bm: TBookmark;
    begin
      DBGrid1.DataSource.DataSet.DisableControls;
      try
        bm := DBGrid1.DataSource.DataSet.GetBookmark;
        try
          i := 0;
          DBGrid1.DataSource.DataSet.First;
          while not DBGrid1.DataSource.DataSet.Eof do begin
            Inc(i);
            FillRow(wrdDataDoc, i,
              DBGrid1.DataSource.DataSet.FieldByName('Name').AsString,
              DBGrid1.DataSource.DataSet.FieldByName('Address1').AsString,
              ..
              );
            DBGrid1.DataSource.DataSet.Next;
          end;
          if Assigned(bm) then
            DBGrid1.DataSource.DataSet.GotoBookmark(bm);
        finally
          DBGrid1.DataSource.DataSet.FreeBookmark(bm);
        end;
      finally
        DBGrid1.DataSource.DataSet.EnableControls;
      end;
    end;