Roll462011,
Cita:
Empezado por Roll462011
...Necesito conocer si el libro de Excel en el que voy a poner datos ya está abierto, si es así utilizarlo sino es así abrirlo para utilizarlo ...
|
Revisa este código:
Código Delphi
[-]
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses ComObj, ActiveX;
function IsObjectAvailable(const ClassName: string): Boolean;
var
ClassID: TCLSID;
begin
Result := Succeeded(CLSIDFromProgID(PWideChar(WideString(ClassName)), ClassID));
end;
function IsObjectActive(const ClassName: string): Boolean;
var
ClassID: TCLSID;
Unknown: IUnknown;
begin
Result := False;
if Succeeded(CLSIDFromProgID(PWideChar(WideString(ClassName)), ClassID)) then
Result := Succeeded(GetActiveObject(ClassID, nil, Unknown));
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Excel : Variant;
FileExcel : String;
i : Integer;
MsgApp : String;
FileExcelOpen : Boolean;
begin
if not IsObjectAvailable('Excel.Application') then
begin
MsgApp := 'Excel no esta Instalado en esta Máquina';
MessageDlg(MsgApp,mtInformation,[mbOK],0);
Exit;
end;
FileExcel := ExtractFilePath(Application.ExeName) + 'TestExcel.xlsx';
FileExcelOpen := False;
if IsObjectActive('Excel.Application') then
Excel := GetActiveOleObject('Excel.Application')
else
Excel := CreateOleObject('Excel.Application');
Excel.DisplayAlerts := True;
Excel.Visible := True;
if (Excel.Workbooks.Count > 0) then
begin
for i := 1 to Excel.Workbooks.Count do
begin
if Excel.Workbooks[i].Name = ExtractFileName(FileExcel) then
begin
MsgApp := Format('El Libro de Excel %s esta Abierto y sera Cerrado',[FileExcel]);
MessageDlg(MsgApp,mtInformation,[mbOK],0);
Excel.Workbooks[i].Close(True);
FileExcelOpen := True;
Break;
end
end
end;
if not FileExcelOpen then
begin
if FileExists(FileExcel) then
begin
Excel.Workbooks.Open(FileExcel);
MsgApp := Format('El Libro de Excel %s Fue Abierto',[FileExcel]);
MessageDlg(MsgApp,mtInformation,[mbOK],0);
end
else
begin
MsgApp := Format('El Libro de Excel %s No Existe',[FileExcel]);
MessageDlg(MsgApp,mtInformation,[mbOK],0);
end;
end;
MsgApp := Format('Excel sera Finalizado',[FileExcel]);
MessageDlg(MsgApp,mtInformation,[mbOK],0);
Excel.Quit;
Excel := Unassigned;
end;
end.
El código anterior en Delphi 7 sobre Windows 7 Professional x32,
realiza diversas operaciones de verificación, apertura y cierre en una instancia de Excel 2010 por medio de
Automatización en Excel.
Revisa esta información:
Espero sea útil
Nelson.