1
votes

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
The article you link to contains a reasonable answer, with code. What's your problem?David Heffernan
The problem is that I do not know how to make it work and if it work because the code isn't very clear.Jordan Borisov
What have you tried? The post by lespaul seems to be pretty straight forward to try.user496736
The code is perfectly clear. What I suggest you do is attempt to write your own code based on this sample and if you get stuck, post your attempt here and include the full text of any error messages.David Heffernan
If I define a macro in my own local excel application with some actions and I want to run this macro throuth a delphi program how can I do it. This guy lespaul just provide some code to how to fill some cells and how to run Process_Report which I do not know is it macro or not. So how can I run my own define macro with action in Excel from Delphi program?Jordan Borisov

1 Answers

9
votes

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.