How to loop an update query on all records of a table (1 Viewer)

macut

New member
Local time
Today, 12:33
Joined
Sep 2, 2014
Messages
2
hi everybody...

I've set a database which has a table in which there are 2 fields "Account" and "Total Accounts". I want to have the amount of total summation of accounts in "Total Accounts" field of each record, which is the result of summation of "Account" values in all previous records till the current one. In order to do this purpose, I copied the value of "Amount" field of each record into "Total Accounts" field of the same record, at first. Then, I tried to add the amount of "Total Accounts" field of every record with just the amount of "Total Accounts" of previous one to earn the actual total amount of that record. I found that I need a VBA loop to do this query for all records (except first record) and so I code it as below, but it has the Run-time error '424' : Object required and it seems that I am in a mistake in definition of strSQL variable:

Code:
Private Sub doDataSegm_Click()


Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String

Set dbs = CurrentDb()
Set rs = dbs.OpenRecordset("Table1", dbOpenTable)

If (rs.RecordCount = 0 Or rs.RecordCount = 1) Then Exit Sub

rs.MoveFirst
rs.MoveNext

    For i = 2 To rs.RecordCount
   
    strSQL = "UPDATE Table1, Table1 as copyTable Set Table1.[Total Accounts] = Table1.[Total Accounts] + [copyTable].[Total Accounts] Where Table1.ID = i and copyTable.ID = i-1"
    
    db.Execute strSQL, dbFailOnError
    rs.MoveNext
    Next i


End Sub
 

jdraw

Super Moderator
Staff member
Local time
Today, 04:03
Joined
Jan 23, 2006
Messages
15,379
macut,

Most articles you'll find on table design will advise you to
Not Store Totals in Tables.

If/When you do the Totalling or other calculation use a query.
 

macut

New member
Local time
Today, 12:33
Joined
Sep 2, 2014
Messages
2
hi every body,

finally I did and correct the code myself and this is my final code which has been tested:

Code:
Dim rs As DAO.Recordset
Dim strSQL As String

Set dbs = CurrentDb()
Set rs = dbs.OpenRecordset("Table1", dbOpenTable)

strSQL = "UPDATE Table1 SET Table1.[Total Accounts] = [Account];"
dbs.Execute strSQL, dbFailOnError

If (rs.RecordCount <= 1) Then Exit Sub

    For i = 2 To rs.RecordCount
   
    strSQL = "UPDATE Table1, Table1 as copyTable Set Table1.[Total Accounts] = Table1.[Total Accounts] + [copyTable].[Total Accounts] Where Table1.ID = " & i & " and copyTable.ID = " & i - 1&
      
    dbs.Execute strSQL, dbFailOnError
    Next i
    
End Sub
 

Users who are viewing this thread

Top Bottom