The VBA code below only executes the query one (1) time. It does NOT replace the table reference in the FROM statement with any subsequent table in the TDF scan.
See attached updated sample DB with VBA (in form 'F01_MainMenu').
Please advise as to how the VBA needs to be modified so that all tables meeting the T100 criteria will have records appended as part of the loop.
Code:
Option Compare Database
Private Sub cmdMergeTables_Click()
'Error handling
On Error GoTo Err_PrematureClose_Click
'Declare variables
Dim tdf As DAO.TableDef
Dim sTable As String
Dim strSQL As String
'Clear the table
CurrentDb.Execute "DELETE * FROM T000_MergedData;", dbFailOnError
'Get the database and associated query
Set db = CurrentDb()
Set qdf = db.QueryDefs("Q_MergeData")
'Start looping through the table definitions
For Each tdf In CurrentDb.TableDefs
sTable = tdf.Name
If Left(sTable, 5) <> "T100_" Then GoTo NEXT_TDF
'I need to auto-replace table reference in 'FROM T100_Org1_IncludeInMerge' with TDF table name
strSQL = "INSERT INTO T000_MergedData ( ORGANIZATION, [MODULE], SOURCE_FIELD, TARGET_FIELD ) " & _
"SELECT ORGANIZATION, MODULE, SOURCE_FIELD, TARGET_FIELD " & _
"FROM " & sTable & ";"
'Apply the new SQL statement to specified query
qdf.SQL = strSQL
'Open query
DoCmd.OpenQuery "Q_MergeData", acViewNormal, acReadOnly
'Empty memory
Set db = Nothing
Set qdf = Nothing
NEXT_TDF:
Next tdf
MsgBox "All done! The T000_MergedData table has been refreshed.", vbInformation, "T000_MergedData Refresh Completed"
'Begin error handling
Exit_PrematureClose_Click:
Exit Sub
Err_PrematureClose_Click:
Resume Exit_PrematureClose_Click
End Sub