Thema: Excel Sheets

Einzelnen Beitrag anzeigen

Benutzerbild von Chemiker
Chemiker

Registriert seit: 14. Aug 2005
1.858 Beiträge
 
Delphi 11 Alexandria
 
#7

AW: Excel Sheets

  Alt 2. Okt 2016, 20:20
Hallo Sidi61,

ich habe einen Fehler in der Zeile:

if ((NOT VarIsEmpty(oExcel))and VarIsEmpty(olevWB)) then
sie muss geändert werden. Von olevWB nach oWB1.

if ((NOT VarIsEmpty(oExcel))and VarIsEmpty(oWB1)) then
Ich habe das Beispiel unter Delphi Berlin mit Office 2016 und Delphi XE5 mit Office 2007 getestet. Einfach ein Form anlegen einen Button drauf und im onClick-Event den Code kopieren.

Delphi-Quellcode:
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.SyncObjs,System.Win.ComObj;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private-Deklarationen }
  public
    { Public-Deklarationen }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
   oExcel: OLEVariant;
   oWB1: OLEVariant;
   oWS1: OLEVariant;
   oWS2: OLEVariant;
begin
   try
     oExcel := CreateOleObject('Excel.Application');
   except
     ShowMessage('Microsoft Excel kann nicht starten.');
     exit;
   end;
   oExcel.Visible:= TRUE;
   // Workbook anlegen
   if (NOT VarIsEmpty(oExcel)) then
   begin
     oWB1:=oExcel.Workbooks.add;
   end;
   if ((NOT VarIsEmpty(oExcel))and(NOT VarIsEmpty(oWB1))) then
   begin
     // Wir legen mal ein neues Sheet an, es soll vor den ersten Sheet eingefügt
     // werden
     oWS1:= oWB1.Worksheets.add(Before:= oWB1.WorkSheets[1]);
     oWS1.Name:= 'Erste Blatt';
     oWS2:= oWB1.Worksheets[2];
     oWS2.Name:= 'Zweites Blatt';
     oWS2.activate;
     ShowMessage('Blatt 2 aktiviert');
     oWS1.activate;
     ShowMessage('Blatt 1 aktiviert');
   end;
   if ((NOT VarIsEmpty(oExcel))and(NOT VarIsEmpty(oWB1))
       and(NOT VarIsEmpty(oWS1))and(NOT VarIsEmpty(oWS2))) then
   begin
     oWS1.Delete; // Wir löschen das neue Sheet
     oWS1:= Unassigned;
   end;
   // Workbook schliesssen
   if (NOT VarIsEmpty(oWB1)) then
   begin
     oWB1.Saved := TRUE; // ohne Nachfragen
     oWB1.Close;
     oWB1:= Unassigned;
   end;
   // Excel schliessen
   if ((NOT VarIsEmpty(oExcel))and VarIsEmpty(oWB1)) then
   begin
     oExcel.Quit;
     oExcel:= Unassigned;
   end;
end;

end.
Bis bald Chemiker
wer gesund ist hat 1000 wünsche wer krank ist nur einen.
  Mit Zitat antworten Zitat