如何使用 Python 参数运行 MS Access 子/函数?

问题描述 投票:0回答:1

我可以使用 Python 运行 MS Access 宏(然后运行 MS Access VBA 函数),如此处所述。不过Access宏好像不能使用参数。

是否有可能直接从 Python 运行 Access VBA 子程序或函数并向其传递参数?我试过了

application.run

VBA代码:

Public Function doNothing()
    MsgBox "Test"
End Function

访问宏3: 正是运行这个函数

Python

import win32api
from win32com.client import Dispatch

objAccess = Dispatch("Access.Application")
objAccess.Visible = True
objAccess.OpenCurrentDatabase(destinationName)

#Working with macro: (but no parameters possible)
objAccess.DoCmd.RunMacro('Macro3') 

#Not working: direct function call
#objAccess.Run('doNothing')

#Also not working:
#objDB = objAccess.CurrentDb()
#objDB.Run('doNothing')

objAccess.Application.Quit() 
python vba database function parameters
1个回答
0
投票

这就是我让它工作的方法:首先,我尝试调用从 Excel 运行的 Access VBA。

Excel VBA代码:

Public Sub openAccess()

Dim acc As Access.Application
Set acc = New Access.Application
    With acc
        .Application.Visible = True
        .OpenCurrentDatabase "C:\Temp\test.accdb"
         With .Application
            .Eval ("doNothing()")
         End With
        .Quit
    End With
Set acc = Nothing

End Sub

然后我也可以找到Python的解决方案。

Python代码:

import win32api,time
from win32com.client import Dispatch
from datetime import date, datetime
  
destinationName = "C:\Temp\test.accdb"
    
#now get the db object and open the  db
objAccess = Dispatch("Access.Application")
objAccess.Visible = True       
objAccess.OpenCurrentDatabase(destinationName)
    
    
#calling a function does work
objAccess.Application.Eval('doNothing()')
    
objAccess.Application.Quit() 

现在,如果我们需要使用函数参数,请注意,在此调用中 Eval() 确实仅将参数作为字符串,例如对于日期参数:

strDay = date.today().strftime("%m/%d/%Y")
objAccess.Application.Eval('doNothing("' + strDay + '")') 

因此,之后Access VBA代码需要再次将输入日期字符串转换回日期:

Public Function doNothing(inputDate As String)
    MsgBox CDate(inputDate) - 10
End Function
© www.soinside.com 2019 - 2024. All rights reserved.