LoginSignup
56
78

More than 5 years have passed since last update.

ExcelからPythonを実行する

Last updated at Posted at 2016-05-28

xlwingsを使って今度はExcel-VBAからPythonを実行して、python上でExcelファイルを操作してみる。

VBAでいいじゃんという話もあるだろうが、VBA書きたくないんだから仕方ないじゃないw

xlwingsの使い方はPython(Xlwings)を使ってExcelを操作してみるに書いたので良かったら参照。

ちなみに環境はMacですが、Windowsでもxlwingsは動きます。

公式ドキュメント

VBA: Calling Python from Excel

手順

概要

  • 実行したいpythonスクリプトを用意
  • pythonを呼ぶマクロを登録
  • xlswings vba moduleをexcleファイルにインポート
  • 実行

実行したいpythonスクリプトを用意

なんでもいいけど、Excelファイルに適当に値を設定するスクリプトを用意してみる。

from xlwings import Workbook, Range

def myfunction():
    wb = Workbook.caller()
    Range('A1').value = "Call Python!"

pythonを呼ぶマクロを登録

Excelファイルを新規作成して、Alt + F11でエディタ開いて、マクロを登録

Sub SampleCall()
    RunPython ("import myproject;myproject.myfunction()")
End Sub

ここのmyprojectがpythonのスクリプト名。

myfunctionが実行したい関数。

xlswings vba moduleをExcelファイルにインポート

xlwings.basというVBAモジュールをファイルにインポートする必要がある。

xlwings.basはインストールしたxlwignsディレクトリに入っている。

パスを調べたい場合、Python Consoleで簡単に調べられる

import xlwings
xlwings.__path__

実行

適当なオブジェクトに作成したマクロSampleCall()を登録して、実行すれば完了。

エラーが出た場合

Macの場合、xlswings vba moduleでは.bash_profileを読み込みんでpythonのパスを設定するみたい。

bash使っている人なら設定されているだろうから問題ないだろうけど、自分みたいにzsh使っている場合は.bash_profileを用意していないので以下のようなエラーが出る。

importError: No module named xlwings

bash_profileを作るか、zshrcを読み込むようにxlwings.basを書き換えてあげる。
書き換える場合は、下の.bash_profile.zshrcに書き換えるだけでいい。

    'Check if .bash_profile is existing and source it
    Res = system("source ~/.bash_profile")
    If Res = 0 Then
        Res = system("source ~/.bash_profile;" & RunCommand & """" & WORKBOOK_FULLNAME & """ ""from_xl""" & " " & Chr(34) & ToPosixPath(Application.Path) & "/" & Application.Name & Chr(34) & ">" & Chr(34) & LOG_FILE & Chr(34) & " 2>&1 &")
    Else
        Res = system(RunCommand & """" & WORKBOOK_FULLNAME & """ ""from_xl""" & " " & Chr(34) & ToPosixPath(Application.Path) & "/" & Application.Name & Chr(34) & ">" & Chr(34) & LOG_FILE & Chr(34) & " 2>&1 &")
    End If

Tips

いちいちxlwings.basをインポートするのがめんどくさい場合は
コンソールで以下のコマンドを実行すれば、インポート済みのExcelファイルと呼び出されるpythonスクリプトを生成してくれる。

xlwings quickstart myproject
56
78
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
56
78