Thema: Delphi Zugriff auf MS Excel

Einzelnen Beitrag anzeigen

Benutzerbild von stoxx
stoxx

Registriert seit: 13. Aug 2003
1.111 Beiträge
 
#33

Re: Zugriff auf MS Excel

  Alt 13. Feb 2009, 14:58
also ich hab da mal gebastelt. Schick, Schick !
Die Lösung gefällt mir besser, als GetActiveOLEObject

Delphi-Quellcode:
unit

  ComObj,
  ActiveX,

  ExcelXP;

  // oder nach Belieben

  // Excel2000;
  // Excel_TLB;

procedure TForm1.Button1Click(Sender : TObject);
var

    eApp : ExcelApplication;

begin

  eapp := SearchExcelAppFromWorkBook('Mappe1');
  eApp.Quit; // Mappe beenden
  eApp := nil; // Excel Instanz beenden


  eapp := SearchExcelAppFromWorkBook(FFileName);
  if not assigned(eapp) then
    eApp := CoExcelApplication.Create;
  


end;

Delphi-Quellcode:
//==============================================================================
// sucht zu einem Workbook (FileName) die passende Excel Application, wenn mehrere
// Instanzen von Excel offen sind
//==============================================================================

function SearchExcelAppFromWorkBook(const aWorkBookName : string) : ExcelApplication;
var
  ROT: IRunningObjectTable;
  Enum: IEnumMoniker;
  Fetched: integer;
  RunningObj: IMoniker;
  Name: PWideChar;
  BindCtx: IBindCtx;
  App : IInterface;

  wb : _WorkBook;

begin
  result := nil;

  try
      OleCheck(CreateBindCtx(0, BindCtx));
      OleCheck(GetRunningObjectTable(0, ROT));
      if ROT.EnumRunning(Enum) = S_OK then
      begin
        Enum.Next(1, RunningObj, @Fetched);
        while RunningObj <> nil do
        begin
          RunningObj.GetDisplayName(BindCtx, nil, Name);

          // ShowMessage('RunningObj.GetDisplayName: ' + Name);

          if Name = aWorkBookName then begin
              ROT.GetObject(RunningObj, app );
              App.QueryInterface(_WorkBook, WB);
              if assigned(WB) then begin
                  // ShowMessage('Gefunden: ' + aWorkBookName);
                  wb.Application.QueryInterface(_Application, result);
                  exit;
               end;
          end;

          Enum.Next(1, RunningObj, @Fetched);
        end;
      end;
  except
      result := nil;
  end;

end; // SearchExcelAppFromWorkBook
Phantasie ist etwas, was sich manche Leute gar nicht vorstellen können.
  Mit Zitat antworten Zitat