3

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?

0

2 Answers 2

2

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

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

See "Excel Object Model Reference".

Sign up to request clarification or add additional context in comments.

2 Comments

+1 At least you explained the cause of the error, unlike me. I just went straight for early binding. I hate late binding.
@David - OTOH, I hardly ever think anything beyond the problem and the solution, which is why I voted your answer... I'm aware of some of the advantages of early binding, with a Delphi IDE however which shouldn't make sense otherwise, one more advantage would be it would play nice with error insight..
2

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!

1 Comment

Not only create a workbook page, but each time, check if there is an ActiveSheet, because the user could have closed the worksheet completely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.