Excecute Excel vba code through Delphi [closed]

2019-10-02 08:39发布

Hi my question is how to execute Excel vba code through Delphi 7 program? I found some articles in internet, which weren't described clearly. One of them was with using OLE : Article

I will be grateful if you can give me sample code with the answer. Tha main problem is that I can't understant the code and I need some help. The variable are not declared and I do not no will it work. Thanks in advance

    unit Macro;

    interface

    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, ActnList, StdCtrls, Buttons, MSObjCtrls, ComObj, ActiveX;

    type
      TForm1 = class(TForm)
        ActionList1 : TActionList;
        btnMacro : TMSBitBtn;
        acMacro : TAction;
        procedure acMacroExecute(Sender : TObject);
      private
        { Private declarations }
      public
        { Public declarations }
      end;

    var
      Form1             : TForm1;

    implementation

    {$R *.dfm}

    procedure TForm1.acMacroExecute(Sender : TObject);
    var
      Excel             : OleVariant;
    begin
      Excel := CreateOleObject('Excel.Application');
      Excel.Workbooks.Open('C:\Documents and Settings\iordan.borisov\Desktop\data.xls');
      Excel.Run('PERSONAL.XLSB!MyMacro'); // <<--- Error here.
      Excel.Quit;

    end;
    initialization
      CoInitialize(nil);
    finalization
      CoUninitialize;

    end.

This code throws a run time exception :


Debugger Exception Notification

Project Project1.exe raised exception class EOleException with message 'OLE error 800A03EC'. Process stopped. Use Step or Run to continue.

on line 34

1条回答
Luminary・发光体
2楼-- · 2019-10-02 09:09

It's pretty much as simple as this:

uses
  ComObj;
....
var
  Excel: OleVariant;
....
Excel := CreateOleObject('Excel.Application');
Excel.Workbooks.Open('myworkbook.xls');
Excel.Run('MyMacro');
Excel.Quit;

Make sure you don't forget to call CoInitializeEx in order to initalize COM.

查看更多
登录 后发表回答