次の方法で共有


Office プログラミングで名前付き引数と省略可能な引数を使用する方法

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

Von Bedeutung

VSTO (Visual Studio Tools for Office)、.NET Framework に依存しています。 COM アドインは、.NET Framework を使用して記述することもできます。 最新バージョンの .NET Core および .NET 5 以降では、Office アドインを作成できません。 これは、.NET Core/.NET 5 以降が同じプロセスで .NET Framework と連携できず、アドインの読み込みエラーにつながる可能性があるためです。 .NET Framework を引き続き使用して、Office 用の VSTO アドインと COM アドインを作成できます。 Microsoft は、.NET Core または .NET 5 以降を使用するように VSTO または COM アドイン プラットフォームを更新しません。 .NET Core と .NET 5 以降 (ASP.NET Core を含む) を利用して、 Office Web アドインのサーバー側を作成できます。

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

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

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

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

Visual Studio を起動します。 [ファイル] メニューの [新規作成]をポイントし、 [プロジェクト]をクリックします。 [ テンプレート カテゴリ ] ウィンドウで、[ C#] を展開し、[ Windows] を選択します。 [テンプレート] ウィンドウの上部を見て、[ターゲット フレームワーク] ボックスに .NET Framework 4 が表示されていることを確認します。 [テンプレート] ウィンドウ 、[ コンソール アプリケーション] を選択します。 [名前] フィールドにプロジェクトの 名前を入力 します。 [OK] を選択. ソリューション エクスプローラーに新しいプロジェクトが表示されます。

参照を追加する

ソリューション エクスプローラーで、プロジェクトの名前を右クリックし、[参照の追加] を選択します。 [参照の追加] ダイアログ ボックスが表示されます。 .NET ページで、コンポーネント名の一覧で Microsoft.Office.Interop.Word を選択します。 [OK] を選択.

ディレクティブを使用して必要なものを追加する

ソリューション エクスプローラーでProgram.cs ファイルを右クリックし、[コードの表示] を選択します。 次の using ディレクティブをコード ファイルの先頭に追加します。

using Word = Microsoft.Office.Interop.Word;

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

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

COM スレッドやタイミングの問題を回避して、「The message filter indicated that the application is busy」(HRESULT 0x8001010A) といった例外が発生しないように、Word アプリケーションは操作中は非表示にし、すべての操作が完了した後に初めて表示されます。

static void DisplayInWord()
{
    var wordApp = new Word.Application();
    // Keep Word invisible during operations to avoid COM threading issues
    wordApp.Visible = false;
    // 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();
    
    // Make Word visible after operations are complete
    wordApp.Visible = true;
}

メソッドの末尾に次のコードを追加して、ドキュメント内のテキストを表示する場所と表示するテキストを定義します。

// 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. . .");

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

Main に次のステートメントを追加します。

DisplayInWord();

Ctrl+F5 キーを押してプロジェクトを実行します。 指定したテキストを含む Word 文書が表示されます。

テキストをテーブルに変更する

ConvertToTableメソッドを使用して、テキストをテーブルで囲みます。 このメソッドには、16 個の省略可能なパラメーターがあります。 次の図に示すように、IntelliSense は省略可能なパラメーターを角かっこで囲みます。 Type.Missingの既定値は、System.Type.Missingの単純な名前です。

ConvertToTable メソッドのパラメーターの一覧

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

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

Ctrl+F5 キーを押してプロジェクトを実行します。

その他のパラメーターを試す

1 つの列と 3 つの行が含まれるようにテーブルを変更し、 DisplayInWord の最後の行を次のステートメントに置き換え、 Ctrl+F5 キーを押します。

range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1);

テーブルの定義済みの形式を指定し、 DisplayInWord の最後の行を次のステートメントに置き換えて、 Ctrl+F5 キーを押します。 形式には、 WdTableFormat クラスの定数を使用できます。

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

次のコードには、完全な例が含まれています。

using System;
using Word = Microsoft.Office.Interop.Word;

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

        static void DisplayInWord()
        {
            var wordApp = new Word.Application();
            // Keep Word invisible during operations to avoid COM threading issues
            wordApp.Visible = false;
            // 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);

            // Make Word visible after all operations are complete
            wordApp.Visible = true;
        }
    }
}