次の方法で共有


選択したセルを含むワークシート行の書式をプログラムで変更する

テキストが太字になるように、選択されたセルを含む行全体のフォントを変更することができます。

適用対象: このトピックの情報は、Excel のドキュメント レベルのプロジェクトおよび VSTO アドインのプロジェクトに適用されます。 詳細については、「Office アプリケーションおよびプロジェクトの種類別の使用可能な機能」を参照してください。

現在の行を太字にし、前に太字にした行を標準にするには

  1. 前に選択されていた行を追跡する静的変数を宣言します。

    static int previousRow = 0;
    
  2. ActiveCell プロパティを使用して、現在のセルへの参照を取得します。

    Excel.Range currentCell = this.Application.ActiveCell;
    
  3. アクティブ セルの EntireRow プロパティを使用して、現在の行を太字でスタイル設定します。

    currentCell.EntireRow.Font.Bold = true;
    
  4. previousRow の現在の値が 0 ではないことを確認します。 0 (ゼロ) は、このコードを初めて使用することを示します。

    if (previousRow != 0)
    
  5. 現在の行が前の行と異なることを確認します。

    if (currentCell.Row != previousRow)
    
  6. 以前に選択されていた行を表す範囲への参照を取得し、その行が太字にならないように設定します。

    Excel.Range rng = (Excel.Range)ws.Rows[previousRow];
    rng.EntireRow.Font.Bold = false;
    
  7. 現在の行を格納して、次のパスで前の行になることができるようにします。

    previousRow = currentCell.Row;
    

    このメソッドを使ったサンプル コード全体を次に示します。

// Keep track of the previously bolded row.
static int previousRow = 0;

private void BoldCurrentRow(Excel.Worksheet ws)
{
    // Work with the current active cell.
    Excel.Range currentCell = this.Application.ActiveCell;

    // Bold the current row.
    currentCell.EntireRow.Font.Bold = true; 

    // If a pass has been done previously, make the old row not bold.
    // Make sure previousRow is not 0 (otherwise this is your first pass through).
    if (previousRow != 0)
    
        // Make sure the current row is not the same as the previous row.
        if (currentCell.Row != previousRow)
        {
            Excel.Range rng = (Excel.Range)ws.Rows[previousRow];
            rng.EntireRow.Font.Bold = false;
        }

    // Store the new row number for the next pass.
    previousRow = currentCell.Row;
}