我使用pythonnet来实例化MS Access。创建实例后,我打算使用OpenCurrentDatabase打开一个文件,但后来我发现了一个python" object"转换为" System.object"通过pythonnet。我的代码是(主要归功于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,但是我无法操纵对象,我认为这是正常的方式,因为(我认为)是对象" to" 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'
我的最终游戏是执行以下操作:
我希望有一个简单的解释,有人可以告诉我如何引用系统.__ ComObject.something.OpenCurrentDatabase和System .__ ComObject.something.Run(Access VBA code,args)。我很感激任何人的帮助。
答案 0 :(得分:1)
我使用以下代码来处理
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()
re: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所述。