[英]xlwings doesn't `get_selection` when run from VBA
我在写这篇文章时有一些不确定性,确切地说是问题所在。 我尝试用Spyder调试问题,以确保没有任何结果。
问题是,当使用Workbook.set_mock_caller(path)
选项时,我的脚本在Spyder中的解释器中运行良好,但在VBA中却无法很好地运行。
我怀疑get_selection()
得到的是空选择,但是由于我无法在中间停止代码,因此我无法确定。
无论如何,我的脚本是我第一次尝试使用该程序包,因此对于以前使用过该程序包的人来说,它不会很复杂。 该函数的作用是通过其第一列合并Excel选择表,并将其余各列加在一起。
def xl_consolidate():
thisWB = xl.Workbook.caller()
thisSlctn = thisWB.get_selection(asarray=True, atleast_2d=True)
thisTable = thisSlctn.value
(m,n) = thisSlctn.shape
r = thisSlctn.row
c = thisSlctn.column
tableDict = dict()
tableVals = thisTable[:, 1:].astype(np.float)
for i in range(m):
thisKey = thisTable[i, 0]
if thisKey not in tableDict:
tableDict[thisKey] = tableVals[i, :]
else:
tableDict[thisKey] += tableVals[i, :]
modTable = sorted(tableDict.keys(), key = lambda k:(-tableDict[k][0], k))
modTable = [np.hstack((key, tableDict[key])) for key in modTable]
thisSlctn.clear()
xl.Range((r, c)).value = modTable
该错误发生在已sorted
函数中,它表示以下内容:
Error
modTable = sorted(tableDict.keys(), key = lambda k:(-tableDict[k][0], k))
IndexError: index 0 is out of bounds for axis 0 with size 0
从VBA调用函数时,我确实做了选择。
作为一个附加问题,我想知道从VBA运行时是否可以调试代码。 这将帮助我解决它。
谢谢您的帮助
当我不选择任何单元格时,我只会收到您的错误。 所以是的,您可能是对的,由于某种原因,它没有得到选择。 您如何称呼RunPython
? 用一个按钮?
但是,您未正确连接modTable
:而不是numpy数组的列表(类似[array([ 2., 8., 8.]), array([ 3., 6., 6.])]
) ,您应该构建一个数组: array([[ 2., 8., 8.],[3., 6., 6.]])
(如果尝试提供列表,使用Python3的xlwings甚至会抱怨的数组。)
至于调试:我可以想到两种可能性(并且都在等待更好的文档):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.