Search code examples
delphiole

Calling existing excel file using OLE - delphi


I have an excel file which contains a format for the data that will be passed in it. Can Someone help me how to open an existing excel file?

var
  myExcel:variant;
begin
  myExcel:=CreateOleObject('Excel.application');
  myExcel.caption:='Summary of Check Issued';
  myExcel.visible:=false;
  myexcel.workbooks.add(1);
end

that statement will create a new excel file but what i want is a statement to just open my existing excel file.


Solution

  • The exact line of code you are looking for is:

    WorkBook := ExcelFile.WorkBooks.Open('yourfilename.xls');
    

    The complete code might look something like this:

    var
       ExcelFile : Variant;
       WorkBook : Variant;
       WorkSheet : Variant;
    
    begin
    
      // Open Excel OLE
      ExcelFile :=  CreateOleObject('Excel.Application');
    
      // Handle WoorkBook
      if not VarIsNull(ExcelFile) then begin
          WorkBook := ExcelFile.WorkBooks.Open('yourfilename.xls');
    
          if not VarIsNull(WorkBook) then begin
          // Handle Sheet
              WorkSheet := WorkBook.WorkSheets.Item['yourSheetName'];
          end;
    
      end; 
    

    Refer to this article for more detailed information.