【问题标题】:Passing A Parameter for a VBA Recordset为 VBA 记录集传递参数
【发布时间】:2015-01-29 07:59:30
【问题描述】:

我有一个查询,它的参数不属于下面的结果列。
当我执行查询时,它通常会弹出。

PARAMETERS SelectedDate DateTime;
Select col1,col2, col3 from qry
where col4 = [SelectedDate]

我需要为 col1 和 col2 创建一个 VBA 记录集。
谁能告诉我如何传递这个参数?有没有可能?

【问题讨论】:

    标签: ms-access vba parameter-passing recordset


    【解决方案1】:

    您可以使用SELECT 语句作为DAO.Recordset 的数据源,然后在打开它之前提供参数值。

    Dim db As DAO.Database
    Dim qdf As DAO.QueryDef
    Dim rs As DAO.Recordset
    Dim strSelect As String
    
    strSelect = "PARAMETERS SelectedDate DateTime;" & vbCrLf & _
        "Select col1,col2, col3 from qry" & vbCrLf & _
        "where col4 = [SelectedDate];"
    Debug.Print strSelect '<-- inspect this in Immediate window; Ctrl+g to go there
    
    Set db = CurrentDb
    Set qdf = db.CreateQueryDef(vbNullString, strSelect)
    qdf.Parameters("SelectedDate").Value = Date '<-- whatever Date/Time value you want here
    Set rs = qdf.OpenRecordset
    

    【讨论】:

      【解决方案2】:

      据我了解,您希望将参数从 VBA 传递到 Access Query?

      如果是这样,您需要在 VBA 中创建一个模块。

      可能是这样的:

      Public Str As String
      
      Public Function str_move() As String
      str_move = Str
      End Function
      

      所以 Str 是 VBA 中的变量。 在您的查询中,您现在可以写 str_move() 并因此得到这个 Str 值。

      注意:模块名称不能与函数名称相同。将模块命名为 m_MoveVariables

      没关系 - 查询中不使用模块名称。

      我希望这对你有用。

      【讨论】:

      • 模块名很重要,你给的代码是行不通的,至少没有修改是不行的。
      • 为什么不起作用?它在这里工作。我从我自己的模块中复制了它......我每天都使用它。
      • 我的评论集中在模块名称与函数名称相同。
      • 我不明白。我写道,名字不能相同。但是这个名字并不重要(只要它们不相等)。这不正确吗?
      【解决方案3】:

      您甚至可以简单地使用 Recordset,而不使用 QueryDef 对象,

      Dim rsObj As DAO.Recordset
      
      Set rsObj = CurrentDB.OpenRecordset("SELECT col1, col2 FROM qry WHERE col4 = " & _
                                          Format(Date(), "\#mm\/dd\/yyyy\#"))
      
      'Date() can be replace with any Date or Date Variable.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多