xlwings从VBA调用python

时间:2015-03-01 04:07:58

标签: python vba excel-vba winapi xlwings

这是我尝试从Excel VBA中调用python脚本后收到的错误[http://docs.xlwings.org/quickstart.html]

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named mymodule

Press Ctrl+C to copy this message to the clipboard.

在哪里可以保存包含以下内容的module.py文件:

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

我已将xlwings.bas作为模块导入Visual Basic编辑器,我在anaconda 2.1.0上有python 2.7.8

$ which python
/c/ana/python

$ pip show xlwings
---
Name: xlwings
Version: 0.2.2
Location: c:\ana\lib\site-packages
Requires:

我假设xlwings.bas文件链接到我的pythonpath但子程序如何知道如何调用module.py文件和/或子程序如何知道module.py文件的位置位于?

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

1 个答案:

答案 0 :(得分:1)

默认情况下,xlwings VBA模块需要Python文件与Excel文件位于同一目录中。这是可以在xlwings VBA模块中更改的PYTHONPATH设置。