从Excel VBA

时间:2017-08-18 18:39:40

标签: excel-vba ms-access vba excel

我正在使用Excel 2013和Access 2013.我的访问查询有一个表单,其中包含2个输入,"开始日期"和"结束日期",然后在访问中运行宏。有没有办法可以使用VBA输入"开始日期"和"结束日期"从excel运行表单访问?这是我尝试过的,但是我收到错误说"操作或方法无效,因为表单或报告没有绑定到表或查询"

Sub RunAccessQuery()

Dim strDatabasePath As String
Dim appAccess As Access.Application
Dim startDate As Date
Dim endDate As Date

startDate = ThisWorkbook.Sheets("sheet1").Range("B2").Value

strDatabasePath = "access database path"
Set appAccess = New Access.Application
With appAccess
    Application.DisplayAlerts = False
    .OpenCurrentDatabase strDatabasePath
    .DoCmd.OpenForm "inputForm", , , "start =" & startDate
    '.Quit
End With
Set appAccess = Nothing

ThisWorkbook.RefreshAll
MsgBox ("Data has been updated")

End Sub

这就是我的表格。点击我运行一个宏,第一个文本框保存变量"开始"第二个包含变量"结束"

enter image description here

1 个答案:

答案 0 :(得分:1)

由于我假设您的表单没有记录源,并且控件未绑定,因此以下内容应该避免您遇到的错误:

Sub RunAccessQuery()

Dim strDatabasePath As String
Dim appAccess As Access.Application
Dim startDate As Date
Dim endDate As Date

startDate = ThisWorkbook.Sheets("sheet1").Range("B2").Value

strDatabasePath = "access database path"
Set appAccess = New Access.Application
With appAccess
    Application.DisplayAlerts = False
    .OpenCurrentDatabase strDatabasePath
    .DoCmd.OpenForm "inputForm"
    .Forms("inputForm").start = startDate
    '.Quit
End With
Set appAccess = Nothing

ThisWorkbook.RefreshAll
MsgBox ("Data has been updated")

End Sub

但是,这仍然只是打开表单并设置开始日期,并在之后立即关闭Access。