Delphi交互式批量創建和刪除多月份表格

職場菊菊子 2024-06-19 13:14:00
前言

在前面的文章中介紹了使用VBA批量創建和刪除12個月份表格。在Delphi中,也可以通過OLE方式,通過跟VBA相同的API去調用Excel。

知識點

Delphi可以通過OLE技術調用Excel。涉及到的方法如下:

功能

方法

新建Excel對象

CreateOleObject('Excel.Application')

獲取打開的Excel對象

GetActiveOleObject('Excel.Application')

操作Excel工作簿和工作表的方法,跟之前在VBA介紹的一模一樣。

需求設計

主要有兩個需求點:

新建一個工作簿,批量新建1-12月份對應的工作表找到當前工作簿,批量刪除1-12月份對應的工作表

代碼實現

按照上面的設計,很容易寫出對應的代碼。邏輯跟VBA保持一致,用到的API也跟VBA完全一樣,只是Delphi對應的語法和VBA略有差異。

unit Unit1;interfaceuses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;type TForm1 =(TForm) Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end;var Form1: TForm1;implementationuses ComObj;{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);var xlsApp, wb, sht: Variant; i: Integer;begin try xlsApp := CreateOleObject('Excel.Application'); xlsApp.Visible := True; wb := xlsApp.Workbooks.Add; for i := 1 to 12 do begin sht := wb.Worksheets.Add(null, wb.Worksheets[wb.Worksheets.Count]); sht.Name := IntToStr(i) + '月'; end; finally wb := UnAssigned; xlsApp := UnAssigned; end;end;procedure TForm1.Button2Click(Sender: TObject);var xlsApp, wb, sht: Variant; i, shtCount, month: Integer;begin xlsApp := GetActiveOleObject('Excel.Application'); xlsApp.Visible := True; xlsApp.DisplayAlerts := False; wb := xlsApp.ActiveWorkbook; shtCount := wb.Worksheets.Count; i := shtCount; while i > 0 do begin sht := wb.Worksheets[i]; month := StrToIntDef(StringReplace(sht.Name, '月', '', [rfReplaceAll]),0); if (month>=1) and (month <= 12) then sht.Delete; i := i-1; end;end;end.效果預覽

上述功能最後的效果如圖所示。

0 阅读:0

職場菊菊子

簡介:感謝大家的關注