对于每个" ConcatID",我想连接" Major"分成一行&#34 ;;"
Source table:
ConcatID Major
A Math
A English
A Theatre
B Math
C Biology
Target table:
A Math; English; Theatre
B Math
C Biology
代码运行并执行我需要它执行的操作,但是我收到此错误"运行时错误' 3021'没有当前记录"在这行代码上
Do While (ID_prev = rs_source![ConcatID].Value And Not (rs_source.EOF))
Option Compare Database
Option Explicit
Sub Concat()
Dim dbs As DAO.Database
Dim rs_source As DAO.Recordset
Dim rs_target As DAO.Recordset
Dim MajorList As String 'Placeholder for concatenating list of college majors
Dim ID_prev As String 'Retains ID from previous record
Set dbs = CurrentDb
Set rs_source = dbs.OpenRecordset("tbl_ConcatMajorsSource") 'many records per student/college
Set rs_target = dbs.OpenRecordset("tbl_ConcatMajorsTarget") 'one record per student/college
dbs.Execute ("DELETE * FROM tbl_ConcatMajorsTarget") 'clear out table
ID_prev = rs_source![ConcatID].Value ' set equal to first ID
MajorList = rs_source![Major].Value ' set equal to first major
rs_source.MoveNext ' move to the second record
Do While Not (rs_source.EOF)
Do While (ID_prev = rs_source![ConcatID].Value And Not (rs_source.EOF))
MajorList = rs_source![Major].Value & "; " & MajorList 'concatenate majors
rs_source.MoveNext
Loop
rs_target.AddNew ' add new record in target table
rs_target![ConcatID].Value = ID_prev ' populate ID
rs_target![Major].Value = MajorList ' populate MajorList
rs_target.Update
ID_prev = rs_source![ConcatID].Value ' set ID_prev to the new ID
MajorList = "" 'blank out MajorList
Loop
rs_source.Close
rs_target.Close
Set rs_source = Nothing
Set rs_target = Nothing
End Sub
提前谢谢!
答案 0 :(得分:0)
这是因为当记录集达到EOF时无法读取记录。因此:
Do While Not rs_source.EOF
If ID_prev = rs_source![ConcatID].Value Then
Exit Do
Else
MajorList = rs_source![Major].Value & "; " & MajorList 'concatenate majors
rs_source.MoveNext
End If
Loop