2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【python3・VBA・xlwings】Excelマクロからpythonモジュールを動かす方法

2
Posted at

はじめに

ExcelのVBAのマクロから、pythonモジュールを実行させて、実行結果を、VBAマクロに出力できないか、調査し、テストした結果、正常に実行されたので、忘備録を兼ねてブログに投稿致します

前提条件

以下の記事にpythonのxlwingsライブラリのインストールと、Excelにアドインを追加する方法の記事をUPしているので、参考にしていただけると幸いです。

Excelマクロの設定方法

Microsoft Visual Basic Editorのメニューからツール参照設定を選択し、xlwingsにチェックを入れて、OKボタンを押す。

VBAでのソースコード

マクロのファイル名をhello.xlsmにして、以下のソースコードをコピペする

Sub CallPython()
    ' hello.py をインポートして my_function を実行
    RunPython "import hello; hello.my_function()"
End Sub

pythonのソースコード

hello.xlsmと同じフォルダ内に、hello.pyというファイルを作成し、以下のpythonのソースコードをコピペする。

import xlwings as xw

def my_function():
    msg = "増田三莉音"
    wb = xw.Book.caller()
    wb.sheets("Sheet1").range('A1').value = msg 

マクロを実行した結果

hello.xlsmにあるマクロを実行した結果は以下の画像のとおりである。

実行前
before.jpg

実行後
after.jpg

最後に

Excelマクロからpythonを実行する方法を検証しました。
自動化ツールを構築、実行する際に便利なので、記事に致しました。

2
2
0

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?