サーバレス練習帳

着眼大局着手小局

【delphi】Excel操作 ⇒ できるぞ!

usesにExcel2000, OleServer, ComObjを忘れずに。

一度エクセルを開けば、「 label1.Caption := WorkSheet.Cells[1,1].Value;」みたいにアクセスできそうです。
簡単 ~ ★

いや、文字列型とか数値型で苦労しそうではあるな。

unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,Excel2000, OleServer;

type
  TForm2 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Label1: TLabel;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  private
    { Private 宣言 }
      ExcelObj   : OleVariant;
     WorkBook   : OleVariant;
     WorkSheet  : OleVariant;
  public
    { Public 宣言 }
  end;

var
  Form2: TForm2;

implementation

uses ComObj;


{$R *.dfm}

procedure TForm2.Button1Click(Sender: TObject);
var
  xlsHandle : HWND;
  xlsWidth  : Integer;
  xlsHeight : Integer;
  WorkRect  : TRect;
begin
  //エクセルが起動中かをハンドルの有無で検査
  xlsHandle := FindWindow('XLMAIN', nil);
  if xlsHandle = 0 then begin
    MessageBox(Handle, 'エクセルは起動していません', '情報', MB_ICONINFORMATION);
  end else begin

    //表示位置を調整
    WorkRect  := Screen.PrimaryMonitor.WorkareaRect;
    xlsWidth  := WorkRect.Right - Self.Width;
    xlsHeight := WorkRect.Bottom - WorkRect.Top;
    SetWindowPos(xlsHandle,
                 HWND_TOP,
                 WorkRect.Left,
                 WorkRect.Top,
                 xlsWidth,
                 xlsHeight,
                 SWP_SHOWWINDOW);

    //表示中のExcelのオブジェクトを取得
    //管理者権限で実行すると失敗する
    ExcelObj := GetActiveOleObject('Excel.Application');

    //表示中のブックに接続
    WorkBook := ExcelObj.ActiveWorkbook;

    //シートオブジェクトを定義(ここではSheet3)
    WorkSheet := Workbook.WorkSheets[3];

    //そのシートをアクティブにする
    WorkSheet.Activate;

    //表示}
    ExcelObj.Visible := True;
  end;
end;

procedure TForm2.Button2Click(Sender: TObject);
begin
  if VarIsEmpty(ExcelObj) then exit;

  //ClearActiveSheetCells;
  WorkSheet.Cells[1,1].Value := 'ABC';
  WorkSheet.Cells[1,1].Interior.ColorIndex := 4;
end;


procedure TForm2.Button3Click(Sender: TObject);
begin
  if VarIsEmpty(ExcelObj) then exit;
  label1.Caption :=  WorkSheet.Cells[1,1].Value;
end;

end.

上記は、参考ページの「01_操作サンプル」のButton3とButton6をコピーして少し書き換えただけです。
参考ページ
[ 400_CreateOleObject によるエクセル操作の基本例 ] - Mr.XRAY