1. 程式人生 > 實用技巧 >對Excel操作(VBA)

對Excel操作(VBA)

{經常用到,但有時會忘記,把大體用法寫在blog中,方便檢視。裡面有每個功能的註解}

uses
ComObj;

 1 procedure TForm1.Button1Click(Sender: TObject);
 2 var
 3   ExcelApp,workbook,sheet:OleVariant;
 4 begin
 5   {建立ExcelApplication}
 6   ExcelApp:=CreateOleObject('Excel.Application');
 7   {新增一工作薄}
 8   workbook := ExcelApp.WorkBooks.Add;
 9
{獲取當前的Sheet,工作薄會自動建立一個sheet} 10 sheet:=workbook.sheets[1]; 11 {新增一Sheet並命名} 12 sheet:=workbook.sheets.add; 13 sheet.Name:='xx'; 14 {Excel是否可見} 15 ExcelApp.visible:=true; 16 17 //range['單元格1:單元格n']或range['單元格1','單元格n'],從單元格1到單元格n的區域 18 sheet.range['A1:C6'].merge; 19 sheet.range['A1:C6
'].select; 20 sheet.range['A1:C6']:='測試點'; 21 sheet.range['D7','G20'].merge; 22 sheet.range['A20:A20'].value:='A20'; //單個單元格 23 //cells(行,列) ,從1開始 24 sheet.cells(10,1):='vvvv'; 25 26 if FileExists('d:\aa.xls') then 27 DeleteFile('d:\aa.xls'); 28 {儲存為檔案} 29 workbook.saveas('d:\aa.xls'); 30 workbook.close(true);//
引數表示是否關閉已改動的工作薄 31 32 {退出Excel程式} 33 ExcelApp.application.quit; 34 ExcelApp:=Unassigned; 35 end;