View Single Post
 
Old 09-30-2018, 11:11 PM
rojam rojam is offline
Senior Member
 
Join Date: Jun 2015
Posts: 191
Default

Rather than basing the flow of your code to an exception, you can get a reference to MS Word via code that doesn't cause and exception:
Code:
type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    function GetWordApplication: IDispatch; //Add this
  public
     { Public declarations }
  end;

var
  Form1: TForm1;


implementation


uses System.Win.ComObj, Winapi.ActiveX;

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  MSWord, Doc1: OLEVariant;
  DocName: String;
  vstart, vend: Integer;
begin
  MsWord := GetWordApplication;
  DocName  := 'C:\Test\Hello.docx';
  Doc1 := MsWord.Documents.Open(DocName);
  MsWord.Visible := False;
  RichEdit1.Text := Doc1.Range.Text;
  vstart := 10;
  vend := 20;
  Doc1.Range(vstart, vend).Select;
  MsWord.Selection.InsertAfter(' textAfter ');
  MsWord.Selection.InsertBefore(' textBefore ');
  Doc1.Save;//this saves to the original file
  MsWord.quit;
end;

function TForm1.GetWordApplication: IDispatch;
var
  ClassID: TGUID;
  Unknown: IUnknown;
  HR: HResult;
begin
  ClassID := ProgIDToClassID('Word.Application');
  HR := GetActiveObject(ClassID, nil, Unknown);
  if (HR = MK_E_UNAVAILABLE) then
    Result := CreateComObject(ClassID) as IDispatch
  else
  begin
    OleCheck(HR);
    OleCheck(Unknown.QueryInterface(IDispatch, Result));
  end;
end;
Reply With Quote