Delete row in Excel from Delphi program
I want to remove rows from Excel with Delphi7 program.
This throws an exception:Excel := CreateOleObject('Exc开发者_开发问答el.Application');
...
Excel.ActiveWorkBook.Rows(row).Delete;
What am I doing wrong?
Rows
is a property of a Worksheet. So this should work:
Excel.ActiveWorkBook.ActiveSheet.Rows[row].Delete;
See "Excel Object Model Reference".
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!
精彩评论