I have the following function that I want to use for creating a PDF from Excel. But when trying to save the PDF I get an OLE error 800A03EC that I simply can't figure out. I use the same approach to create PDF from Word and that works just fine.
function xlsCreatePdf(aInput: string; aOutput: string = ''): string;
var
FileDoc: OleVariant;
FilePDF: OleVariant;
ExcelBook: ExcelWorkbook;
PdfName: string;
ExcelApp: ExcelApplication;
begin
Result := '';
if aOutput = '' then
begin
PdfName := Folders.DirOutput + ExtractFileName(aInput);
PdfName := ChangeFileExt(PdfName, '.pdf');
end
else
PdfName := aOutput;
if (Files.Validate(aInput)) then
begin
if not Assigned(ExcelApp) then
ExcelApp := xlsInitialize;
FileDoc := aInput;
ExcelBook := ExcelApp.Workbooks.Open(FileDoc,
EmptyParam, EmptyParam, EmptyParam,
EmptyParam, EmptyParam, EmptyParam,
EmptyParam, EmptyParam, EmptyParam,
EmptyParam, EmptyParam, EmptyParam,
EmptyParam, EmptyParam, DefaultLCID);
FilePdf := PdfName;
ExcelBook.SaveAs(FilePdf, xlTypePDF,
EmptyParam, EmptyParam,
False, False,
xlNoChange, xlUserResolution, False,
EmptyParam, EmptyParam, EmptyParam, DefaultLCID);
xlsFreeAndNil(ExcelApp);
if (Files.Validate(PdfName)) then
Result := PdfName
else
Result := '';
end;
end;
I initialize Excel using
function xlsInitialize: ExcelApplication;
var
ExcelApp: ExcelApplication;
begin
DefaultLCID := LOCALE_USER_DEFAULT;
ExcelApp := CreateOleObject('Excel.Application') as ExcelApplication;
if Assigned(ExcelApp) then
begin
Result := ExcelApp;
ExcelApp.Visible[DefaultLCID] := True;
end
else
raise Exception.Create('Cannot initialize Excel application');
end;
And it should be closed using
procedure xlsFreeAndNil(var ExcelApp: ExcelApplication);
var
i: integer;
begin
if Assigned(ExcelApp) then
begin
for i := 0 to ExcelApp.WorkBooks.Count - 1 do
ExcelApp.WorkBooks.Close(DefaultLCID);
ExcelApp.Quit;
Pointer(ExcelApp) := Nil;
end;
end;
I am using Delphi XE7 and Excel 2010 - the Office TLB used is 2010
xlsFreeAndNil
proc, which has a for-loop but doesn't use for-loop variable in it. – teran