【问题标题】:OpenRecordset and Eval()OpenRecordset 和 Eval()
【发布时间】:2017-10-27 08:32:20
【问题描述】:

我的程序的一般解释:

  1. 我在表单上为用户输入做参考控制。 (开始日期前) 2017 年 8 月 1 日和 2017 年 8 月 31 日之前的结束日期)
  2. 然后我的查询基于参数运行并返回单个值:ex) 12345.23
  3. 运行 VBA 函数。

问题:querydef 对先前打开的查询一无所知。因此,我想在 VBA 中提供参数,但从这一点上我一无所知:

Set qry = CurrentDb.QueryDefs("2_Total")
Set rst = qry.OpenRecordset
For Each prm In qry.Parameters
    prm.Value = Eval(prm.Value)
Next

我的 SQL 代码:

SELECT Sum(dbo_SO_SalesHistory.DollarsSold) AS SumOfDollarsSold
FROM dbo_SO_SalesHistory
HAVING (((dbo_SO_SalesHistory.InvoiceDate) Between [Forms]![RUN]![textBeginOrderDate] And [Forms]![RUN]![textendorderdate]));

这里是完整的代码:

Option Compare Database

Option Explicit
Public Function TRANS2()

    Dim xlApp As Excel.Application
    Dim xlWB As Excel.Workbook
    Dim xlWS As Excel.Worksheet
    Dim acRng As Variant
    Dim xlRow As Integer

    Dim qry As QueryDef
    Dim rst As Recordset
    Dim prm As DAO.Parameter
    Set xlApp = New Excel.Application
    Set xlWB = xlApp.Workbooks.Open("C:\Users\J\Desktop\August 2017.xlsx")
    Set xlWS = xlWB.Worksheets("Totals")

    xlRow = (xlWS.Columns("K").End(xlDown).Row)
    Set qry = CurrentDb.QueryDefs("2_Total")
    Set rst = qry.OpenRecordset
    For Each prm In qry.Parameters
        prm.Value = Eval(prm.Value)
    Next

    Dim c As Integer
    c = 11   'C is the one that stores column number, in which c=1 means column A, 11 is for column K, 12 for Column L
    xlRow = xlRow + 11

     Do Until rst.EOF
        For Each acRng In rst.Fields
            xlWS.Cells(xlRow, c).Formula = acRng
            c = c + 1
        Next acRng
        xlRow = xlRow + 1
        c = 1
        rst.MoveNext
        If xlRow > 25 Then GoTo rq_Exit
    Loop


rq_Exit:
    rst.Close
    Set rst = Nothing
    Set xlWS = Nothing
    xlWB.Close acSaveYes
    Set xlWB = Nothing
    xlApp.Quit
    Set xlApp = Nothing
    Exit Function

End Function

附言我可以将单元格设置为 DSum() 返回的值,但我想按照我的方式进行操作。 我的好参考是https://msdn.microsoft.com/en-us/library/office/ff193967.aspx

编辑:

Set qry = CurrentDb.QueryDefs("2_Total")

For Each prm In qry.Parameters
    prm.Value = Eval(prm.Value)
Next
Set rst = qry.OpenRecordset

我在 For Each 之后移动了 Set rst = qry.OpenRecordset,现在我得到了

您输入的表达式包含无效语法。

在线prm.Value = Eval(prm.Value) 对此的任何建议将不胜感激。

【问题讨论】:

    标签: vba forms ms-access input parameters


    【解决方案1】:

    您的 sql 查询在语法上是错误的。如果没有 GROUP BY 子句,则不能使用 HAVING 子句。我认为您需要使用WHERE 子句,如下所示:

    SELECT Sum(dbo_SO_SalesHistory.DollarsSold) AS SumOfDollarsSold
    FROM dbo_SO_SalesHistory
    WHERE (((dbo_SO_SalesHistory.InvoiceDate) Between [Forms]![RUN]![textBeginOrderDate] 
    And [Forms]![RUN]![textendorderdate]));
    

    【讨论】:

    • 这是一个好点!但我得到的参数太少了。预计2。设置 rst = qry.OpenRecordset 时出错。我不认为 querydef 知道参数
    • 您能看一下编辑吗?我非常感谢您的帮助。提前谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 2015-11-10
    • 1970-01-01
    相关资源
    最近更新 更多