LoginSignup
34
42

More than 3 years have passed since last update.

xlwingsを使うぜ

Last updated at Posted at 2014-12-21

まえがき

Excel Advent Calendar 2014
に空きがあったので、
前々からやりたかった「xlwings」の記事を書いた。
ちなみに僕はBlogあるので、Qiitaに何もなかったからいい機会だ。

xlwingsとは?

VBAでマクロなんて書きたくない人用にPythonでマクロが書けるモジュール。

公式サイトはここですね。
xlwings

インストール

pip install xlwings

virtualenvでインストールすると上手く実行できないようだ(多分)。
OSのPythonにインストールした方がいい。

サンプルの実行

ここにクイックスタートが有る。
しかし、僕は少しハマったのでクイックではなくなったが・・。

まず、Excel自体をどこかに保存しておく。
僕はMac OS Xを使ってるので、

/Users/shinriyo/Documentsへ、「ブック1.xlsx」の名前でExcelファイルを保存した。
※日本語でOK!でしたが、怖い人は半角英数字で。

mymodule.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np
from xlwings import Workbook, Range

def rand_numbers():
    """ produces standard normally distributed random numbers with shape (n,n)"""
    wb = Workbook.caller()  # Creates a reference to the calling Excel file
    n = Range('Sheet1', 'B1').value  # Write desired dimensions into Cell B1
    rand_num = np.random.randn(n, n)
    Range('Sheet1', 'C3').value = rand_num

のように「mymodule.py」を「ブック1.xlsx」と同じ階層に置く。
同じ階層に置くことが重要!(大事なことなので二回言いました。)

/Library/Python/2.7/site-packages/xlwingsxlwings.basファイルがあるはず。

↓このように。
bas.png

マクロを作成し、
Screen Shot 2014-12-21 at 7.20.43 PM.png

VBAのコードは

Sub RandomNumbers()
    RunPython ("import mymodule; mymodule.rand_numbers()")
End Sub

そうしましたら、マクロ上でこのようにインポート。
import.png

そして、Excel上のB1には任意の数字を記載。

Screen Shot 2014-12-21 at 8.19.26 PM.png

RandomNumbersを実行!

Screen Shot 2014-12-21 at 7.27.18 PM.png

すると先ほどの画像のようになる。
たてよこに5追加される。

Screen Shot 2014-12-21 at 8.00.39 PM.png

Range('Sheet1', 'C3').value = u'日本語'

などで日本語も出来るので実験してみるといい。

34
42
1

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
34
42