将数据从 table 插入集合 vba 访问

insert data from table to collection vba access

我是 VBA 访问的新手,我想做的是将数据从 table 放入一个集合,但是当我这样做并检查集合时,所有行都有我加载的最后一行的数据。

Public Function projectStart() As Collection

    Dim cn As New ADODB.connection

    Dim rs As New ADODB.Recordset
    
    Set cn = CurrentProject.connection
    
    Dim sqlQuery As String

    Set projectStart = New Collection
    
    
    sqlQuery = "select * from p6projects"
    rs.Open sqlQuery, cn
    Do Until rs.EOF
        Dim cashFlow As New cashFlow
        
        cashFlow.letIdproject = rs!id
        cashFlow.letStartDate = rs!startDate
        cashFlow.letBlstartdate = rs!blStartDate
        projectStart.Add cashFlow
        
        rs.MoveNext
    Loop
    
    rs.Close
    Set rs = Nothing
    
    cn.Close
    Set cn = Nothing
    
End Function

我正在从 table 加载 10 行,当我打印它们时向我显示,任何行中的数据相同。

10 2/6/2019 2/6/2019
10 2/6/2019 2/6/2019
10 2/6/2019 2/6/2019
10 2/6/2019 2/6/2019
10 2/6/2019 2/6/2019
10 2/6/2019 2/6/2019
10 2/6/2019 2/6/2019
10 2/6/2019 2/6/2019
10 2/6/2019 2/6/2019
10 2/6/2019 2/6/2019

在大多数情况下,当您使用

rst!StartDate  

好吧,你正在返回 FIELD object。这不是一个值,而是一个实际的 DAO object 类型的字段。

在“大多数”情况下,如果您要转换为字符串,在大多数情况下访问会自动为您执行此操作。

但是,collections 能够保存字符串,甚至 object 类型。因此,在您的代码中,您实际上是在向字段 object 而不是值添加引用。

所以,你需要这样做:

cashFlow.letIdproject = rs!id.Value
cashFlow.letStartDate = rs!startDate.Value
cashFlow.letBlstartdate = rs!blStartDate.Value

所以,现在您将值保存到 collection 而不是对字段控件的引用。 如果您保存对该字段的引用,那么对于保存的该字段列引用的所有实例,它将是您所在的任何行。

编辑: 从上面看,.value 实际上不应该是必需的。

显示我们在 collection?

中输入的内容

这会起作用: cashFlow.letIdproject = rs!ID cashFlow.letStartDate = rs!开始日期 cashFlow.letBlstartdate = rs!blStartDate

Dim c As cashFlow
For Each c In projectStart
  Debug.Print c.ID, c.StartDate, c.letBlstartDate

下一个

我们的 class 模块呢?好吧,我们假设这个 class 模块名为 cashFlow。

Option Compare Database
Option Explicit
  
Public letIdproject as long
Public letStartDate as date
Public letBlstartdate as date

您必须提供有关自定义 class 模块外观的更多信息,但上述代码方法应该有效。

VBA: Difference in two ways of declaring a new object? (Trying to understand why my solution works)

问题在于您如何声明 class 对象:

Public Function projectStart() As Collection

    Dim cn As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    Dim sqlQuery As String
    Dim cashFlow As cashFlow   '<<< declare outside of the loop
    
    Set cn = CurrentProject.Connection
    Set projectStart = New Collection
    sqlQuery = "select * from p6projects"
    rs.Open sqlQuery, cn
    Do Until rs.EOF
        Set cashFlow = New cashFlow  'set inside the loop
        cashFlow.letIdproject = rs!ID
        cashFlow.letStartDate = rs!StartDate
        cashFlow.letBlstartdate = rs!blStartDate
        projectStart.Add cashFlow
        rs.MoveNext
    Loop
    
    rs.Close
    Set rs = Nothing
    
    cn.Close
    Set cn = Nothing
    
End Function

最好避免声明变量 As New(如果您记得的话),尤其是在这种情况下。