我已经使用 pythonnet 来实例化 MS Access。创建实例后,我打算使用 OpenCurrentDatabase 打开一个文件,但随后我发现 python“对象”被 pythonnet 转换为“System.object”。我的代码是(主要感谢 Gord Thompson ):
代码
import clr
clr.AddReference('System')
t = System.Type.GetTypeFromProgID('Access.Application')
access = System.Activator.CreateInstance(t)
print(access)
access.OpenCurrentDatabase(r'C:\Users\Test.accdb')
access.Visible = True
num = 1
rtrn_val = access.Run('TestLink', num)
print(rtrn_val)
代码成功地实例化了 MS Access,但是我无法以我认为是正常的方式操作对象,这归功于(我认为)“对象”到“System.__ComObject”的转换发生并且可以是在错误跟踪中看到。
错误跟踪
>>> import clr
>>> clr.AddReference('System')
<System.Reflection.RuntimeAssembly object at 0x0000000004163CC0>
>>> t = System.Type.GetTypeFromProgID('Access.Application')
>>> access = System.Activator.CreateInstance(t)
>>> print(access)
System.__ComObject
>>> access.OpenCurrentDatabase(r'C:\Users\Test.accdb')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: '__ComObject' object has no attribute 'OpenCurrentDatabase'
我的最终目标是执行以下操作:
在 Python 中:
- 从网站下载信息(主要使用 selenium)
- 通过从 Python 调用 VBA 函数将信息从网站发送到 MSAccess
在 Access 中:
- 被Python发起后,运行一堆例程处理 下载的数据并插入到表中
- 返回一个值给最初调用VBA的Python代码 功能
我希望有人能给我一个简单的解释,告诉我如何引用 System.__ComObject.something.OpenCurrentDatabase 和 System.__ComObject.something.Run(Access VBA code, args)。我感谢任何人在这方面的帮助。
- 我宁愿不使用 IronPython,因为我需要使用其他 Python 模块(例如 Selenium),由于 IronPython 的 pip 问题(也许它们与 IronPython 不兼容),我无法在 IronPython 中加载这些模块)
- 如果我必须使用 IronPython,我将需要在 CPython 和 IronPython 之间调用函数,在网上阅读了大量内容后,我仍然不确定如何实现这一点
请您参考如下方法:
我得到了以下代码可以使用
- Python 2.7.13,32 位
- python 网2.3.0
- Access 2013,32 位
import clr
import sys
print(sys.version)
sys.path.append(r"C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Access\15.0.0.0__71e9bce111e9429c")
clr.AddReference("Microsoft.Office.Interop.Access")
import Microsoft.Office.Interop.Access as Access
access = Access.ApplicationClass()
access.OpenCurrentDatabase(r"C:\Users\Public\Database1.accdb")
# (the currently-opened database contains the following function)
#
# Public Function AddTwoLongIntegers(i As Long, j As Long) As Long
# AddTwoLongIntegers = i + j
# End Function
function_returned = access.Run("AddTwoLongIntegers", 4, 10)
print(function_returned) # a tuple: (14, 4, 10)
print("The sum is {0}".format(function_returned[0])) # just the return value
access.Quit()
回复:Python3
我还用 Python 3.6.2(32 位)尝试了上面的代码,但它不有效。我可以运行一个不带参数的 Sub,但是每当我尝试调用带有参数的 Sub 或 Function 时,Python 代码都会失败
IndexError: tuple assignment index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:/Users/Gord/PycharmProjects/pythonnet_test/main.py", line 20, in <module>
function_returned = access.Run("AddTwoLongIntegers", 4, 10)
SystemError: <bound method 'Run'> returned a result with an error set
目前这似乎是 Python 3.5 及更高版本的问题,如所讨论的 here .
