【发布时间】:2021-07-27 12:54:30
【问题描述】:
我正在使用 Python 对 Excel 宏进行单元测试。在测试以下宏时,我需要将字典对象传递给它。
testDict.xlsm 中的代码:
Function GetItemCount(dict As Variant) As Integer
GetItemCount = dict.Count
End Function
我的测试代码如下所示,基于 comtypes 项目中的test_dict.py:
test_comtypes_w_dict.py
from comtypes.client import CreateObject
import win32com.client as win32
d = CreateObject("Scripting.Dictionary", dynamic=True)
d.Add("Test", "An item")
filename = 'testDict.xlsm'
xl = win32.Dispatch("Excel.Application")
wb = xl.Workbooks.Open(filename)
count = xl.Application.Run(filename+'!Module1.GetItemCount', d)
assert count == 1
运行测试时,会引发 TypeError。
Traceback (most recent call last):
File "C:\Users\[..]\test_comtypes_w_dict.py", line 11, in <module>
count = xl.Application.Run(filename+'!Module1.GetItemCount', d)
File "C:\Users\[..]\AppData\Local\Temp\gen_py\3.9\00020813-0000-0000-C000-000000000046x0x1x9.py", line 44654, in Run
return self._ApplyTypes_(259, 1, (12, 0), ((12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17), (12, 17)), 'Run', None,Macro
File "C:\Users\[..]\venv\lib\site-packages\win32com\client\__init__.py", line 467, in _ApplyTypes_
self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args), TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object.
我尝试从对 CreateObject 的调用中删除 dynamic=True。然后测试运行,但我在 Excel 中出现异常:
运行时错误“424”:
需要对象
在 Excel VBA IDE 中调试并运行 TypeName(dict) 时,结果为“Variant()”。
如何以正确识别的方式将字典传递给宏?
作为一种解决方法,我将尝试在宏中生成字典,将其返回给 Python 并将其传递给我要测试的宏。但是,如果可能的话,我想避免这种复杂的方法。
【问题讨论】:
-
如果这不是一个愚蠢的问题,你为什么要使用两种不同的方法(comtypes 和 win32com)来创建调度接口?如果我使用 win32.dispatch("Scripting.Dictionary") 而不是 CreateObject 调用,我的代码版本运行良好并将字典正确传递给 Excel 测试函数,并返回计数 1。
-
@DS_London 这不是一个愚蠢的问题。我从win32com开始,但没有在其中找到CreateObject。是否包含在内?
-
您已经在使用该方法...... win32.Dispatch() 方法要么创建一个新对象,要么附加到一个已经在运行的对象。
标签: python excel com win32com comtypes