Search code examples
delphidelphi-10.2-tokyo

Delphi - open next file from a list once procedure finishes on the first


I have a total of 3214 .doc. I need to open the first file, copy its contents, paste it in a RichEdit, extract some text, insert it into a database then move on to the next file and repeat the procedure.

So far I've managed to:

  • Open the 1st .doc/any 1 .doc only
  • Copy the content and paste it in the RichEdit
  • Extract the text from the RichEdit
  • Insert the extracted text into the database
  • Close the opened .doc and clear the content of RichEdit

I've loaded all 3214 filenames, in order, into a Memo.

Once I finish with the 1st file from the list, how do I now make it move to the next .doc from the list and do the same thing, repeating this till I finish all the 3214 .doc files? Currently reading about loops but I can't figure it out yet.

Code so far:

procedure TForm1.Button4Click(Sender: TObject);
var
  content: string;
  StartPos: Integer;
  endPos: Integer;
  i: integer;
  fname: string;
  WordApp : Variant;    
begin
  WordApp := CreateOleObject('Word.Application');
  for i := 1 to 1 do    
    fname := Memo1.Lines[i - 1];
  WordApp.Visible := True;
  WordApp.Documents.Open('C:\Users\tcsh\Desktop\all\'+fname);
  WordApp.ActiveDocument.Select;
  WordApp.Selection.Copy;
  RichEdit1.Lines.Add(WordApp.Selection);
  WordApp.documents.item(1).Close;
  WordApp.Quit;

  content:= RichEdit1.Text;    
  //<text extract code is here>    
  begin
    //<sql code is here>
  end;

  RichEdit1.Clear;
  Edit1.Clear;
  Edit2.Clear;
  Edit3.Clear;
  Edit4.Clear;
  Edit5.Clear;
  Edit7.Clear;
  Edit8.Clear;
  //the TEdit's hold the extracted text so the sql can retrieve it from them and insert into the database
end;

Solution

  • for i := 1 to 1 do
    

    Hmmm, that will only run once..

    You may also want to try:

    • Create the WordApp object in each iteration ,
    • Add a time delay in between each iteration (using Sleep and Application.ProcessMessages) (as LU RD points out this is not necessary)

    Code sample below:

      for i := 0 to Memo1.Lines.Count - 1 do
      begin
        WordApp := CreateOleObject('Word.Application');
        fname := Memo1.Lines[i];
        WordApp.Visible := True;
        WordApp.Documents.Open(fname);
        WordApp.ActiveDocument.Select;
        WordApp.Selection.Copy;
        Memo2.Lines.Add(WordApp.Selection);
        Memo2.Lines.Add('===');
        WordApp.documents.item(1).Close;
        WordApp.Quit;
        //Sleep(1000);  -> not needed
        //Application.ProcessMessages;
      end;