Excelのセル操作
文字とセル
Excelアドインプロジェクトを新規に作成します。
セルのダブルクリックに対応するイベントハンドラを実装します。
private void ThisAddIn_BeforeDoubleClick(object s, Excel.Range Target, ref bool Cancel) { }
作成したイベントハンドラを登録します。
private void ThisAddIn_Startup(object sender, System.EventArgs e) { this.Application.SheetBeforeDoubleClick += new Microsoft.Office.Interop.Excel .AppEvents_SheetBeforeDoubleClickEventHandler( this.ThisAddIn_BeforeDoubleClick); }
セル内に文字列を表示させるコードを実装します。
private void ThisAddIn_BeforeDoubleClick(object s, Excel.Range Target, ref bool Cancel) { // 文字列を表示 this.Application.Cells[1, 1] = "ほげほげふがふが"; MessageBox.Show("文字列を表示"); }
セル内の文字列の書式を変更するコードを実装します。
private void ThisAddIn_BeforeDoubleClick(object s, Excel.Range Target, ref bool Cancel) { // 文字列を表示 this.Application.Cells[1, 1] = "ほげほげふがふが"; MessageBox.Show("文字列を表示"); // 文字列のプロパティを変更 ((Excel.Range)this.Application.Cells[1, 1]).Font.Bold = true; ((Excel.Range)this.Application.Cells[1, 1]).Font.Color = 0x000000ff; // BBGGRR MessageBox.Show("文字列のプロパティを変更"); }
セルサイズを変更するコードを実装します。
private void ThisAddIn_BeforeDoubleClick(object s, Excel.Range Target, ref bool Cancel) { // 文字列を表示 this.Application.Cells[1, 1] = "ほげほげふがふが"; MessageBox.Show("文字列を表示"); // 文字列のプロパティを変更 ((Excel.Range)this.Application.Cells[1, 1]).Font.Bold = true; ((Excel.Range)this.Application.Cells[1, 1]).Font.Color = 0x000000ff; // BBGGRR MessageBox.Show("文字列のプロパティを変更"); // セルの大きさを変更 ((Excel.Range)this.Application.Cells[1, 1]).ColumnWidth = 50; ((Excel.Range)this.Application.Cells[1, 1]).RowHeight = 50; MessageBox.Show("セルの大きさを変更"); }
実行すると、セルのダブルクリック後に、文字列の表示、文字列のプロパティ変更、セルサイズの変更を順に行います。
なお、この例においても、登録されたCOMアドインを削除しておく必要があります。
セルの罫線
のプロジェクトを使用します。
セルの罫線を設定するコードを記述します*1。
private void ThisAddIn_BeforeDoubleClick(object s, Excel.Range Target, ref bool Cancel) { // 文字列を表示 this.Application.Cells[1, 1] = "ほげほげふがふが"; MessageBox.Show("文字列を表示"); // 文字列のプロパティを変更 ((Excel.Range)this.Application.Cells[1, 1]).Font.Bold = true; ((Excel.Range)this.Application.Cells[1, 1]).Font.Color = 0x000000ff; // BBGGRR MessageBox.Show("文字列のプロパティを変更"); // セルの大きさを変更 ((Excel.Range)this.Application.Cells[1, 1]).ColumnWidth = 50; ((Excel.Range)this.Application.Cells[1, 1]).RowHeight = 50; MessageBox.Show("セルの大きさを変更"); // セルの罫線を変更 ((Excel.Range)this.Application.Cells[1, 1]).BorderAround( missing, Excel.XlBorderWeight.xlMedium , Excel.XlColorIndex.xlColorIndexNone, 0x00ff0000); MessageBox.Show("セルの罫線を変更"); }