Set value in a query when opening a form

I

Ivor Williams

I have in a database an append query which has a Yes/No field Append. The
query appends only those records where the Append field value is set to No
(0). In the OnOpen event of a form, I want to first run the append query to
add any new records, then set the value of the Append field to Yes (-1),
then finish opening or loading the form. How can I do this programmaticaly?

Ivor
 
G

GeoffG

Ivor:

You can do this using DAO.

In the VBA editor, open the Tools menu, select References, and, in the
References dialog, select Microsoft DAO 3.6. Close the References dialog.

In the database window, create a new Update query to update the Append field
to True (ie put True in the "Update To" Row) if the Append field is False
(ie put False in the "Criteria" Row).

You can now execute the Append and Update queries in the Form's Open event.

Here is some sample code for doing this, which assumes the Append query is
named "qryAppend" and the Update query is named "qryUpdate":


Private Sub Form_Open(Cancel As Integer)

Const QRY_APPEND As String = "qryAppend"
Const QRY_UPDATE As String = "qryUpdate"

Dim objDB As DAO.Database
Dim objQDF As DAO.QueryDef
Dim lngRecsAppended As Long

' Instantiate Database object:
Set objDB = CurrentDb()

' Point to the APPEND query:
Set objQDF = objDB.QueryDefs(QRY_APPEND)

' Execute the APPEND query:
objQDF.Execute

' See if the query appended any records:
lngRecsAppended = objQDF.RecordsAffected

' If no records were appended, finish:
If lngRecsAppended = 0 Then GoTo Finish

' Poitn to the UPDATE query:
Set objQDF = objDB.QueryDefs(QRY_UPDATE)

' Execute the query:
objQDF.Execute

' Update this form's recordset:
Me.Requery

Finish:

' Optional: Show message to user:
MsgBox "Records Appended = " & CStr(lngRecsAppended) _
& vbNewLine & vbNewLine _
& "The above number of records were appended " _
& "to the target table and updated in the source " _
& "table.", vbOKOnly + vbInformation, _
"Information"

Set objQDF = Nothing
Set objDB = Nothing

End Sub


Incidentally, on a small point, it would seem natural to rename the field
"Appended".

Regards
Geoff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top