みむらです。IronPython ってのがあるので、ちょちょいと。
仕組みとしては、Visual Studio の VSTO (Visual Studio Tools for Office) を使って、
Office 向けのアドインを作って、その中で IronPython を動かそうーってこと。
結果としてはこんな感じ!
とりあえず、VSTO の書き方とかは割愛して。
ソースはここに:
https://github.com/mimura1133/mm_Python_for_Excel
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
namespace ExcelAddIn1
{
public partial class ThisAddIn
{
public static string Code = "";
static ScriptEngine _python;
static ScriptScope _python_scope;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
_python = Python.CreateEngine();
_python_scope = _python.CreateScope();
_python_scope.SetVariable("Application", Application);
_python_scope.SetVariable("Function", Application.WorksheetFunction);
_python_scope.SetVariable("Cells", Application.Cells);
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
public static void Run()
{
var cc =_python.CreateScriptSourceFromString(Code);
cc.Execute(_python_scope);
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
}
メインソースはこんな感じ!
Python.CreateEngine() で、 Python のエンジン作って、
Scope に対して、 SetVariable を使って、参照をがしがし。( python で言うところの、 import )
あと、どこかから Run が実行されたらコンパイルして実行する仕掛け。
動作例ですと、「Run」 ボタンですね。
これ使った場合、 Function 以下に、Excel の関数が存在していて、
Cells 以下に、各セル情報が入っているので、キー入力を捕まえてくれば、Python によるマクロも可能かも。
制作時間30分だから、とっても汚くて、実装がふざけた感じになっているけど、許してね。