I want to apply an SQL query to one Access table, from which it is retrieving data from a table in another Access file. I\'ve looked around on this subject and can\'t seem t
You prefer not to use a link to the table in the external database, but that choice is a complication when you want to use DAvg
. However, since you're doing this with VBA code, you can ditch DAvg
and do what you need in 2 steps:
UPDATE
.For step #1, test this as a new query in the Access query designer ...
SELECT Avg(Field1InExternalDB)
FROM TableInExternalDB IN 'C:\VB\ExternalDB.accdb'
WHERE Field2InExternalDB=Year(Date());
Assuming that query returns the correct value, adapt your VBA code to retrieve the same value.
Dim db As DAO.database
Dim strSelect As String
Dim varAvg As Variant
strSelect = "SELECT Avg(Field1InExternalDB)" & vbCrLf & _
"FROM TableInExternalDB IN 'C:\VB\ExternalDB.accdb'" & vbCrLf & _
"WHERE Field2InExternalDB=Year(Date());"
'Debug.Print strSelect
Set db = CurrentDb
varAvg = db.OpenRecordset(strSelect)(0)
Debug.Print Nz(varAvg, 0) ' see note
Note that query will return Null when no rows include Field2InExternalDB
values which match the current year. That is why varAvg
is declared as Variant
. Later Nz(varAvg, 0)
will give you zero instead of Null.
Then you can use a parameter query for your UPDATE
and supply Nz(varAvg, 0)
as the parameter value.
Dim qdf As DAO.QueryDef
Dim strUpdate As String
strUpdate = "UPDATE TableInCurrentDB" & vbCrLf & _
"SET [Field1InCurrentDB]=[pAvg]" & vbCrLf & _
"WHERE [Field2InCurrentDB]='1';"
'Debug.Print strUpdate
Set qdf = db.CreateQueryDef(vbNullString, strUpdate)
qdf.Parameters("pAvg") = Nz(varAvg, 0)
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing