C#で作ったdllをExcel/VBAから呼び出す方法。

課題

  • 関数にsummaryを書き、xmlを生成したが、Excel/VBAでは表示されない。
  • 下記のコードの意味がよく分からない。
[ComRegisterFunctionAttribute]
private static void RegisterFunction(Type type)
{
    Registry.ClassesRoot.CreateSubKey(
      GetSubKeyName(type, "Programmable"));
    RegistryKey key = Registry.ClassesRoot.OpenSubKey(
      GetSubKeyName(type, "InprocServer32"), true);
    key.SetValue("", System.Environment.SystemDirectory + @"\mscoree.dll",
      RegistryValueKind.String);
}
[ComUnregisterFunctionAttribute]
private static void UnregisterFunction(Type type)
{
    Registry.ClassesRoot.DeleteSubKey(
                    GetSubKeyName(type, "Programmable"), false);
}
private static string GetSubKeyName(Type type,
  string subKeyName)
{
    System.Text.StringBuilder s = new System.Text.StringBuilder();
    s.Append(@"CLSID\{");
    s.Append(type.GUID.ToString().ToUpper());
    s.Append(@"}\");
    s.Append(subKeyName);
    return s.ToString();
}

調査(途中)

  • COMとは、Mincrosoftが提唱する技術仕様。この仕様に基づいてデータのやり取りができるパーツのことをCOMコンポーネントと呼ぶ。COMコンポーネントは、どの言語からも使用できる。
  • CLSIDとは、COMコンポーネント固有のID。世界中の開発者がCOMコンポーネントを作ってもかぶらないようになっている。
  • C#のTypeクラスはGUIDというプロパティを持っている。
  • ComRegisterFunctionAttributeは属性でComRegisterFunctionとしても同じ。
  • ComRegisterFunctionを付けると、RegAsm.exeがその関数を呼ぶようになる。
  • CLSIDのsub keyとして、ProgrammableとInprocServer32を作成し、InprocServer32にmscoree.dllを設定すれば良い。