访问VBA循环以更新列

时间:2015-11-12 15:08:34

标签: loops access-vba

我有一个包含大约500,000条记录的Access数据库。有一个特定的列具有事务引用。

形式如下:

Transaction_Ref
CDY1053N1
CDY1053N2
CDY1053N3
JFD215D1
JFD215D2 

CDY1053N和JFD215D是客户参考,后面的1,2,3等是交易编号。

我正在寻找的是一个循环,它将更新名为" Group"的列。这将转到第1行,并循环访问数据库以查找类似于CDY1053N的事务引用并分配组ID,例如:

Transaction_Ref   Group_ID
CDY1053N1            1
CDY1053N2            1
CDY1053N3            1
JFD215D1             2
JFD215D2             2

有什么想法吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这可能不是最好或最优雅的方式(特别是你拥有的记录数),但这对我的一小组测试记录起作用。

我假设Transaction_RefGroup_ID在同一张表格中,我称之为tblTransactions

我还假设您可能希望在新数据上运行此操作,因此在循环并重置值之前已使Group_ID为空。这可能意味着为一组记录分配了Group_ID的不同值(例如,您的记录是否在此子流的后续运行之间更改顺序)。

如果这是一个问题,您需要稍微调整一下。

Public Sub AssignGroupID()

    Dim db As DAO.Database
    Dim rs As DAO.Recordset
    Dim sql As String
    Dim i As Integer

    Set db = CurrentDb

    ' Clear the Group_ID column (in case you want to run this more than once)
    sql = "UPDATE tblTransactions Set Group_ID = Null"
    db.Execute sql

    ' Open your table with the Transaction_Ref and Group_ID fields
    Set rs = db.OpenRecordset("tblTransactions")

    ' Zero the counter
    i = 0

    ' Start the loop (set it to end when it gets to the last record)
    Do While Not rs.EOF

        ' Only update Group_IDs that haven't got a value yet
        If IsNull(rs!Group_ID) Then

            ' Push the counter on
            i = i + 1

            ' Update all Group_IDs with current counter number that
            ' match the customer reference of the current record
            sql = "UPDATE tbltransactions Set Group_ID = " & i & " WHERE " _
                & "Left(tblTransactions.Transaction_Ref, Len(tblTransactions.Transaction_Ref) -1) = '" _
                & Left(rs!Transaction_Ref, Len(rs!Transaction_Ref) - 1) & "'"
            db.Execute sql

        End If

        ' Move to the next record
        rs.MoveNext

    Loop

    'clean up
    rs.Close
    Set rs = Nothing
    Set db = Nothing

End Sub