Access SQL Query from another DB

15,769

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:

  1. First retrieve the average from the external table.
  2. Use that step #1 average in your 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
Share:
15,769
user2937941
Author by

user2937941

Updated on June 14, 2022

Comments

  • user2937941
    user2937941 almost 2 years

    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 to get solutions to work.

    Based on this source http://support.microsoft.com/kb/113701, I came up with the following, but still have no luck.

    sSQL = "UPDATE TableInCurrentDB 
    SET [Field1InCurrentDB]= DAvg('Field1InExternalDB','[;database=C:\VB\ExternalDB.accdb].[TableInExternalDB]','Field2InExternalDB= & Year(Now()) & ') 
    WHERE [Field2InCurrentDB]='1';"
    DoCmd.RunSQL sSQL
    

    I know that the error lies somewhere in the reference to the external DB, because the code works fine if the tables are in the same database. However, it's tough to tell exactly what's wrong because the error I get is 'Unknown'.

    How can I modify this statement to update an Access table from another Access database's table?