PhysiologyWeb Logo  Search
PhysiologyWeb Loading...

Delphi Code - Open and Close an Existing Excel File
Here is a simple Delphi procedure that opens and closes a Microsoft Excel file. The code serves to demonstrate the basic logic and does nothing other than open and close the file. The most relevant parts of the code are highlighted. Comments are included to explain the code. If you copy and paste the code into your program, be sure to change the form and procedure names to match your setup. For additional Excel automation solutions, see Microsoft Excel Automation with Delphi.
procedure TForm1.OpenAndCloseAnExistingExcelFile(Sender: TObject);
var
ExcelFileName: String;
ExcelApplication, ExcelWorkbook, ExcelWorksheet: Variant;
begin
//be sure ComObj and Variants units are included in the "uses" clause

ExcelFileName := 'C:\PhysiologyWeb\delphi_code_examples\excel_file.xlsx'; //replace file name with the name of your file

ExcelApplication := Null;
ExcelWorkbook := Null;
ExcelWorksheet := Null;

try
//create Excel OLE
ExcelApplication := CreateOleObject('Excel.Application');
except
ExcelApplication := Null;
//add error/exception handling code as desired
end;

If VarIsNull(ExcelApplication) = False then
begin
try
ExcelApplication.Visible := True; //set to False if you do not want to see the activity in the background
ExcelApplication.DisplayAlerts := False; //ensures message dialogs do not interrupt the flow of your automation process. May be helpful to set to True during testing and debugging.

//Open Excel Workbook
try
ExcelWorkbook := ExcelApplication.Workbooks.Open(ExcelFileName);
//reference
//https://docs.microsoft.com/en-us/office/vba/api/excel.workbooks.open
except
ExcelWorkbook := Null;
//add error/exception handling code as desired
end;

If VarIsNull(ExcelWorkbook) = False then
begin
//connect to Excel Worksheet using either the ExcelApplication or ExcelWorkbook handle
try
ExcelWorksheet := ExcelWorkbook.WorkSheets[1]; //[1] specifies the first worksheet
//or
//ExcelWorksheet := ExcelWorkbook.WorkSheets.Item[1];
//or
//ExcelWorksheet := ExcelApplication.WorkSheets[1];
//or
//ExcelWorksheet := ExcelApplication.WorkSheets.Item[1];

//or if the name of the worksheet is known, either of the following two lines of code may be used. Use appropriate worksheet name.
//ExcelWorksheet := ExcelWorkbook.WorkSheets['Sheet1'];
//ExcelWorksheet := ExcelWorkbook.WorkSheets.Item['Sheet1'];

//reference
//https://docs.microsoft.com/en-us/office/vba/api/Excel.Worksheets.Item
except
ExcelWorksheet := Null;
//add error/exception handling code as desired
end;

If VarIsNull(ExcelWorksheet) = False then
begin
ExcelWorksheet.Select;
//work on the Excel worksheet as needed
end;
end;
finally
ExcelApplication.Workbooks.Close;
ExcelApplication.DisplayAlerts := True;
ExcelApplication.Quit;

ExcelWorksheet := Unassigned;
ExcelWorkbook := Unassigned;
ExcelApplication := Unassigned;
end;
end;
end;






Posted: Saturday, December 5, 2020