Share via


方法: Office プログラミングで名前付き引数と省略可能な引数を使用する (C# プログラミング ガイド)

Visual C# 2010 に導入された名前付き引数と省略可能な引数により、C# プログラミングの利便性、柔軟性、および読みやすさが向上しました。また、これらの機能によって、Microsoft Office オートメーション API などの COM インターフェイスへのアクセスも容易になります。

次の例では、ConvertToTable メソッドに 16 個のパラメーターがあります。これらのパラメーターは、列と行の数、書式設定、境界線、フォント、色などの表の特性を表します。ほとんどの場合どのパラメーターにも特定の値を指定する必要がないため、16 個のパラメーターはすべて省略可能です。ただし、名前付き引数と省略可能な引数を使用しない場合は、各パラメーターに対して値またはプレースホルダー値を指定する必要があります。名前付き引数および省略可能な引数を使用する場合は、プロジェクトに必要なパラメーターのみに値を指定します。

以下の手順を実行するには、Microsoft Office Word がコンピューターにインストールされている必要があります。

[!メモ]

お使いのマシンで、Visual Studio ユーザー インターフェイスの一部の要素の名前や場所が、次の手順とは異なる場合があります。これらの要素は、使用している Visual Studio のエディションや独自の設定によって決まります。詳細については、「Visual Studio の設定」を参照してください。

新しいコンソール アプリケーションを作成するには

  1. Visual Studio を起動します。

  2. [ファイル] メニューの [新規作成] をポイントし、[プロジェクト] をクリックします。

  3. [テンプレート カテゴリ] ペインで、[Visual C#] を展開し、[Windows] をクリックします。

  4. [テンプレート] ペインの最上部で、[.NET Framework 4][ターゲット フレームワーク] ボックスに表示されていることを確認します。

  5. [テンプレート] ペインの [コンソール アプリケーション] をクリックします。

  6. [名前] フィールドにプロジェクトの名前を入力します。

  7. [OK] をクリックします。

    ソリューション エクスプローラーに新しいプロジェクトが表示されます。

参照を追加するには

  1. ソリューション エクスプローラーで、プロジェクト名を右クリックし、[参照の追加] をクリックします。[参照の追加] ダイアログ ボックスが表示されます。

  2. [.NET] ページの [コンポーネント名] のボックスの一覧で、[Microsoft.Office.Interop.Word] を選択します。

  3. [OK] をクリックします。

必要な using ディレクティブを追加するには

  1. ソリューション エクスプローラーで、Program.cs ファイルを右クリックし、[コードの表示] をクリックします。

  2. コード ファイルの先頭に、次の using ディレクティブを追加します。

    using Word = Microsoft.Office.Interop.Word;
    

Word 文書にテキストを表示するには

  1. Program.cs の Program クラスでは、Word アプリケーションおよび Word 文書を作成する次のメソッドを追加します。Add メソッドには、4 つの省略可能なパラメーターがあります。この例では、それらのパラメーターの既定値を使用します。そのため、呼び出しステートメントには引数を指定する必要がありません。

    static void DisplayInWord()
    {
        var wordApp = new Word.Application();
        wordApp.Visible = true;
        // docs is a collection of all the Document objects currently 
        // open in Word.
        Word.Documents docs = wordApp.Documents;
    
        // Add a document to the collection and name it doc. 
        Word.Document doc = docs.Add();
    }
    
  2. 文書のテキストを表示する場所と表示するテキストの内容を定義するメソッドの末尾に次のコードを追加します。

    // Define a range, a contiguous area in the document, by specifying
    // a starting and ending character position. Currently, the document
    // is empty.
    Word.Range range = doc.Range(0, 0);
    
    // Use the InsertAfter method to insert a string at the end of the
    // current range.
    range.InsertAfter("Testing, testing, testing. . .");
    

アプリケーションを実行するには

  1. Main を呼び出すための次のステートメントを追加します。

    DisplayInWord();
    
  2. Ctrl キーを押しながら F5 キーを押してプロジェクトを実行します。指定したテキストを含む Word 文書が表示されます。

表のテキストを変更するには

  1. ConvertToTable メソッドを使用して、表のテキストを囲みます。このメソッドには、16 個の省略可能なパラメーターがあります。次の例に示すように、IntelliSense では、省略可能なパラメーターを角かっこで囲みます。

    ConvertToTable のパラメーター

    ConvertToTable メソッドのパラメーターのリスト

    名前付き引数と省略可能な引数を使用すると、変更するパラメーターのみの値を指定できます。DisplayInWord メソッドの末尾に次のコードを追加して、単純な表を作成します。この引数では、range のテキスト文字列内のコンマで、テーブルのセルを区切るように指定します。

    // Convert to a simple table. The table will have a single row with
    // three columns.
    range.ConvertToTable(Separator: ",");
    

    旧バージョンの C# では、次のコードに示すように、ConvertToTable の呼び出しに各パラメーターの参照引数が必要です。

    // Call to ConvertToTable in Visual C# 2008 or earlier. This code
    // is not part of the solution.
    var missing = Type.Missing;
    object separator = ",";
    range.ConvertToTable(ref separator, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing,
        ref missing);
    
  2. Ctrl キーを押しながら F5 キーを押してプロジェクトを実行します。

他のパラメーターを試してみるには

  1. 1 つの列と 3 つの行を含むように表を変更するには、DisplayInWord の最後の行を次のステートメントに置き換え、Ctrl キーを押しながら F5 キーを押します。

    range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1);
    
  2. 表の定義済みの形式を指定するには、DisplayInWord の最後の行を次のステートメントに置き換え、Ctrl キーを押しながら F5 キーを押します。 形式は WdTableFormat のいずれかの定数とすることができます。

    range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1,
        Format: Word.WdTableFormat.wdTableFormatElegant);
    

使用例

この例のコード全体を次に示します。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Word = Microsoft.Office.Interop.Word;


namespace OfficeHowTo
{
    class WordProgram
    {
        static void Main(string[] args)
        {
            DisplayInWord();
        }

        static void DisplayInWord()
        {
            var wordApp = new Word.Application();
            wordApp.Visible = true;
            // docs is a collection of all the Document objects currently 
            // open in Word.
            Word.Documents docs = wordApp.Documents;

            // Add a document to the collection and name it doc. 
            Word.Document doc = docs.Add();

            // Define a range, a contiguous area in the document, by specifying
            // a starting and ending character position. Currently, the document
            // is empty.
            Word.Range range = doc.Range(0, 0);

            // Use the InsertAfter method to insert a string at the end of the
            // current range.
            range.InsertAfter("Testing, testing, testing. . .");

            // You can comment out any or all of the following statements to
            // see the effect of each one in the Word document.

            // Next, use the ConvertToTable method to put the text into a table. 
            // The method has 16 optional parameters. You only have to specify
            // values for those you want to change.

            // Convert to a simple table. The table will have a single row with
            // three columns.
            range.ConvertToTable(Separator: ",");

            // Change to a single column with three rows..
            range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1);

            // Format the table.
            range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1,
                Format: Word.WdTableFormat.wdTableFormatElegant);
        }
    }
}

参照

概念

名前付き引数と省略可能な引数 (C# プログラミング ガイド)