【问题标题】:Running Access Form from Excel VBA从 Excel VBA 运行访问表单
【发布时间】:2018-01-27 12:31:24
【问题描述】:

我正在使用 Excel 2013 和 Access 2013。我的访问查询有一个表单,它接受 2 个输入,“开始日期”和“结束日期”,然后在 Access 中运行一个宏。有没有办法可以使用 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

这就是我的表单的样子。点击我运行一个宏,第一个文本框保存变量“start”,第二个保存变量“end”

【问题讨论】:

  • 请提供表格上的数据(记录来源,上面有哪些控件等)。
  • 这里有 2 个文本框,您可以在其中填写开始日期和结束日期(第一个文本框保存变量“开始”,第二个保存变量“结束”。然后按钮上的按钮将运行单击时的宏。什么是记录源?
  • 我没有收到该错误。 DB 打开,表单打开,DB 关闭。我什至用.Visible = True 确认。但是,在我将代码更改为:"start = #" & startDate & "#" 之前,表单不会被过滤到所需的记录。什么是表单的 RecordSource - 表、查询、SQL 语句?
  • 表单只是运行一个宏。我不认为它附加到查询或表格
  • 那你为什么要使用 OpenForm WHERE CONDITION 参数呢?从您的代码中删除它。

标签: excel ms-access vba


【解决方案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。

【讨论】:

  • " .Forms("inputForm").start = startDate " 这就是我要找的。之后我只是放了一个 .DoCmd.RunMacro “宏”来运行表单应该运行的宏。我只是不知道如何在表单中设置变量。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-10
  • 2022-08-14
  • 1970-01-01
  • 1970-01-01
  • 2016-05-01
相关资源
最近更新 更多