在VBA / ADO中,基于来自许多记录的串联字段值创建rs字段

问题描述 投票:-1回答:2

我有一个包含2个字段的MDB表:

+-------------+------------------+
| salesperson | Transaction_Date |
+-------------+------------------+
| John        | 12/11/2018       |
| John        | 13/11/2018       |
| John        | 18/11/2018       |
| Steeve      | 23/12/2018       |
| Steeve      | 29/12/2018       |
+-------------+------------------+

在VBA(在Excel中)我希望通过ADO创建以下格式:

+-------------+----------------------------------+
| salesperson |  Transaction_Date_Concatenated   |
+-------------+----------------------------------+
| John        | 12/11/2018-13/11/2018-18/11/2018 |
| Steeve      | 23/12/2018-29/12/2018            |
+-------------+----------------------------------+

每个销售人员的Transaction_Dates数量可能从1到30不等。

以下SQL为每个销售人员创建一条记录,但它当然不会产生连接字段,尽管它看起来像我想要的方向

SQL = " SELECT SalesPerson, max(Date)  as value1  FROM 0TargetTemplate   GROUP BY SalesPerson"
sql excel vba ms-access access-vba
2个回答
0
投票

据我所知,仅使用SQL无法实现。您需要使用VBA函数迭代记录并构造分隔的字符串。

Allen Browne创建了一个现有的例子,可以找到here

对于您的特定任务,您可以按以下方式调用该函数:

select
    [0TargetTemplate].SalesPerson, 
    ConcatRelated
    (
        "[0TargetTemplate].Transaction_Date", 
        "[0TargetTemplate]", 
        "[0TargetTemplate].SalesPerson = '" & [0TargetTemplate].SalesPerson & "'",
        "[0TargetTemplate].Transaction_Date",
        "-"
    ) as Transaction_Date_Concatenated
from
    [0TargetTemplate];

0
投票

使用link中建议的代码和函数,我在VBA Access中编写了一个过程,但在Set rs =语句中得到错误“Too few parameters”。虽然在VBA模块中正确引用,但我已尝试在VBA EXCEL中使用正确的连接,但得到关于“ConcatRelated”功能无法识别的错误

Sub test()
SQL = "SELECT [tblOrders].CompanyName, ConcatRelated ('[tblOrders].Transaction_Date',[tblOrders], [tblOrders].SalesPerson =' [tblOrders].SalesPerson', [tblOrders].Transaction_Date) AS Transaction_Date_Concatenated FROM tblOrders;"
Set rs = CurrentDb.OpenRecordset(SQL)
 On Error GoTo resultsetError
 dbValue = rs!Variable
 MsgBox dbValue, vbOKOnly, "RS VALUE"
resultsetError:
 MsgBox "Error Retrieving value from database", vbOKOnly, "Database Error"

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.