如何使用ADO记录集基于现有表创建新表并将记录集(新表)设置为表单的记录源?

时间:2013-03-19 05:45:44

标签: vba ms-access-2007 access-vba

我想使用ADO记录集来创建基于现有表的新表。然后我想将新表设置为我的表单的记录源。我知道我可以创建一个查询并将查询设置为我的表单的记录源但是有可能,如果我不想使用这种方法?我希望表单的记录源仅在表单加载时存在。这是我所做的,但仍然无法将表单的记录源设置为我的记录集。

Private Sub Form_Load()

Dim cnn As ADODB.Connection
Set cnn = CurrentProject.Connection
Dim rst As New ADODB.Recordset
rst.ActiveConnection = cnn
Dim mySql As String
'create tblfrmQryOnHold based on tblOnHold
mySql = "SELECT tblDisposition.ID, tblDisposition.DateRecorded, tblDisposition.OrderNo, tblDisposition.ArticleNo, "
mySql = mySql & "tblDisposition.Description, tblDisposition.Process, tblDisposition.Defects, tblDisposition.RefNo, "
mySql = mySql & "tblDisposition.PostedBy, tblDisposition.Status, tblDisposition.Attachment, tblDisposition.Engineer, "
mySql = mySql & "tblDisposition.Remarks, tblDisposition.ReviewClose, tblDisposition.ScrapNo, tblDisposition.HoldbackNo, "
mySql = mySql & "tblDisposition.ProductionRemarks, tblDisposition.HoldbackQuantity, tblDisposition.HoldbackNum INTO "
mySql = mySql & "frmQryOnHold FROM tblDisposition;"

rst.Open mySql
'set form frmOnHold record source to form frmQryOnHold
Forms![frmOnHold].RecordSource = frmQryOnHold
End Sub

我收到此错误“当对象关闭时不允许操作”,该错误引用哪个对象?

2 个答案:

答案 0 :(得分:1)

您似乎正在使用两种不同的想法。

Private Sub Form_Load()

Dim cnn As ADODB.Connection
Set cnn = CurrentProject.Connection
Dim rst As New ADODB.Recordset
rst.ActiveConnection = cnn
Dim mySql As String
'create tblfrmQryOnHold based on tblOnHold
''Using aslias t for tblDisposition for clarity
mySql = "SELECT t.ID, t.DateRecorded, t.OrderNo, t.ArticleNo, "
mySql = mySql & "t.Description, t.Process, t.Defects, t.RefNo, "
mySql = mySql & "t.PostedBy, t.Status, t.Attachment, t.Engineer, "
mySql = mySql & "t.Remarks, t.ReviewClose, t.ScrapNo, t.HoldbackNo, "
mySql = mySql & "t.ProductionRemarks, t.HoldbackQuantity, t.HoldbackNum INTO "
mySql = mySql & "frmQryOnHold FROM tblDisposition As t;"

''Action query, so execute it aginst a connection
''This will fail if the table already exists, so it would be 
''much better to use DELETE FROM ... and INSERT INTO ...
''which would also cut down or bloat. However, the very best
''solution would be to just use a query on tblDisposition 
cnn.Execute mySql

''You now have created the table frmQryOnHold and can use it as @SoupyC 
''shows, or, if you wish to use recordset, as you seem to imply, then you want:

   With rst
     Set .ActiveConnection = cnn
     ''Something like this
     .Source = "select * from frmQryOnHold"
     .LockType = adLockOptimistic
     .CursorType = adOpenKeyset
     .CursorLocation = adUseClient
     .Open
  End With

'set form frmOnHold record source to form frmQryOnHold
Set Forms![frmOnHold].Recordset = rst


'set form frmOnHold record source to form frmQryOnHold
Forms![frmOnHold].RecordSource = frmQryOnHold
End Sub

如果您只是将一个表分配给一个记录源,那么纯DAO就是您的选择。

答案 1 :(得分:0)

你需要在RecordSource周围加上引号:

Forms![frmOnHold].RecordSource = "frmQryOnHold"