Jonas Jasas
Jonas Jasas

Reputation: 43

Delete row in Excel from Delphi program

I want to remove rows from Excel with Delphi7 program.
This throws an exception:

Excel := CreateOleObject('Excel.Application');  
...  
Excel.ActiveWorkBook.Rows(row).Delete;  

What am I doing wrong?

Upvotes: 3

Views: 6446

Answers (2)

David Heffernan
David Heffernan

Reputation: 612993

The following works for me:

var
  Excel: ExcelApplication;
  Workbook: ExcelWorkbook;
  Sheet: ExcelWorksheet;
begin
  Excel := CoExcelApplication.Create;
  Workbook := Excel.Workbooks.Add(EmptyParam, LOCALE_USER_DEFAULT);
  Sheet := Workbook.ActiveSheet as ExcelWorksheet;
  Sheet.Range['A1','A1'].EntireRow.Delete(EmptyParam);
end;

Note that I'm using early binding which makes life much easier. Just include the Excel2000 unit and this code will work for you.

Using early binding will allow you to catch errors like this at compile time rather than getting hard to diagnose runtime errors.

If you want to continue with late binding then, as Sertac states, this works:

Excel.ActiveSheet.Rows[1].Delete;

Don't forget to create a workbook first though!

Upvotes: 2

Sertac Akyuz
Sertac Akyuz

Reputation: 54812

Rows is a property of a Worksheet. So this should work:

Excel.ActiveWorkBook.ActiveSheet.Rows[row].Delete;

See "Excel Object Model Reference".

Upvotes: 2

Related Questions