微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 win32com 和 comtypes 将字典传递给 Excel 宏

如何解决使用 win32com 和 comtypes 将字典传递给 Excel 宏

我正在使用 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),17)),'Run',None,Macro
File "C:\Users\[..]\venv\lib\site-packages\win32com\client\__init__.py",line 467,in _ApplyTypes_
        self._oleobj_.InvokeTypes(dispid,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 并将其传递给我要测试的宏。但是,如果可能,我想避免这种复杂的方法

解决方法

上面的代码混合了两个不同的库来创建 COM 对象。

替换

d = CreateObject("Scripting.Dictionary",dynamic=True)

d = win32.Dispatch('Scripting.Dictionary')

并免除 comtypes,除非某些其他功能需要它。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。