Using the CreateOleObject method has inherent advantages for Word document operations. Compared with the access to the control methods provided by delphi, the CreateOleObject method is "closer" to the operation of the WORD core because it directly uses the VBA language pair provided by OFFICE. Program the operations of the WORD document.
The following is the experiment I did on this machine, and the machine software configuration is as follows:
Windows xp+delphi7.0+OFFICE 2003
This program is very simple. An edit and a button are placed on the page. Every time a button is clicked, the content in the edit will be automatically added to the word document in the background. The file will be automatically saved in the main program when the program is closed. in the directory.
unit main;
interface
//If you want to use CreateOleObject to operate on the WORD document, you should use
//Include Comobj statement and WordXP statement in the statement
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Comobj, WordXP, Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
PRocedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
// procedure Button2Click(Sender: TObject);
Private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
//Declare these two variables as global variables
FWord: Variant;
FDoc: Variant;
Implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
Begin
FWord.Selection.TypeParagraph;
FWord.Selection.TypeText(Text := form1.Edit1.Text);
end;
procedure TForm1.FormCreate(Sender: TObject);
Begin
//First create the object and give a prompt if an exception occurs
try
FWord := CreateOleObject('Word.application');
//Is the execution of the WORD program visible? When the value is False, the program is executed in the background
FWord.Visible := False;
except
ShowMessage('Create a word object failed!');
Exit;
end;
//First create a new page in the open Word, and then type "Hello," + Enter + "World!"
try
FDoc := FWord.Documents.Add;
FWord.Selection.TypeText(Text := 'Hello,');
FWord.Selection.TypeParagraph;
FWord.Selection.TypeText(Text := 'World! ');
except
on e: Exception do
ShowMessage(e.Message);
end;
end;
//Save the file contents to the current directory when the program is closed and named after test.doc
//Closing the WORD program at the same time
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
Begin
FDoc.SaveAs(ExtractFilePath(application.ExeName) +'test.doc');
FWord.Quit;
FWord := Unassigned;
end;
end.
In addition, the operations on other OFFICE files are relatively similar, so I will not go into details. This method can also complete more complex document operations through references to more complex VBA macros in WORD files.