从@xlfunc使用Range时出错

时间:2016-02-28 17:55:51

标签: xlwings

我使用xlwings 0.6.4。如果从python提示符执行,这些行的工作原理如下:

from xlwings import xlfunc, Range, Workbook
wb = Workbook.active()
Range('B1').value = 'set'

但是,如果我将代码放入@xlfunc宏,在Excel中加载UDF(Windows7中的Excel2016)并执行" = test_set()",我会收到错误。

from xlwings import xlfunc, Range, Workbook

@xlfunc
def test_set():
    wb = Workbook.active()
    Range('B1').value = 'set'
    return 'set ok!'

错误是:

pythoncom error: Python error invoking COM method.

Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\win32com\server\policy.py", line 277, in _
Invoke_
    return self._invoke_(dispid, lcid, wFlags, args)
  File "C:\Python27\lib\site-packages\win32com\server\policy.py", line 282, in _
invoke_
    return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None)
  File "C:\Python27\lib\site-packages\win32com\server\policy.py", line 585, in _
invokeex_
    return func(*args)
  File "C:\Python27\lib\site-packages\xlwings\server.py", line 179, in Call
    return ToVariant(obj(*pargs, **kwargs))
  File "c:\users\az\projects\test_set\test_set.py", line 6, in test_set
    Range('B1').value = 'set'
  File "C:\Python27\lib\site-packages\xlwings\main.py", line 901, in value
    self.row1, self.col1, row2, col2), data)
  File "C:\Python27\lib\site-packages\xlwings\_xlwindows.py", line 273, in set_v
alue
    xl_range.Value = data
  File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 565, in
__setattr__
    self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -214682
7284), None)

请帮忙!我做错了什么?!

1 个答案:

答案 0 :(得分:1)

用户定义的函数只能操作调用单元格,这意味着您可以通过xlwing.Range进行阅读,但无法为其分配值。您只能通过返回单个值(如数字或字符串)或2d形状(如嵌套列表或数组公式的numpy数组)来更改单元格的值。