Parameterizing Table Names or conditionally selecting from a table based on table existence doesn't work in database that I know of at the sql level. Instead you have to dynamically create the SQL.
Below is an example that creates a two-dimensional array, that contains a list of table names with it's phone number column name. Builds a sql string dynamically and sets a query definition to that sql string. Presumably you'd call this on start up or whenever else you need it.
It uses Vadim's implementation of Contains but you could have queried MsysObjects instead. It also requires an existing MasterList
query def.
Sub Test()
Dim tableNames(3, 2) As String
tableNames(0, 0) = "Table1"
tableNames(0, 1) = "PhoneNumber"
tableNames(1, 0) = "Table2"
tableNames(1, 1) = "Phone"
tableNames(2, 0) = "Table3"
tableNames(2, 1) = "PhoneNo"
Dim i As Integer
Dim sql As String
For i = 0 To UBound(tableNames, 1)
If Contains(CurrentDb.TableDefs, tableNames(i, 0)) Then
sql = sql + " SELECT Name, " & tableNames(i, 1) & " as PhoneNumber "
sql = sql + " FROM Table1 " & tableNames(i, 0)
sql = sql + " UNION"
End If
Next
If Len(sql) >= Len(" UNION") Then
sql = Left(sql, Len(sql) - Len(" UNION"))
Else
sql = ""
End If
If sql <> "" Then
CurrentDb.QueryDefs("MasterList").sql = sql
End If
End Sub
Public Function Contains(col As Variant, key As Variant) As Boolean
Dim obj As Variant
On Error GoTo err
Contains = True
obj = col(key)
Exit Function
err:
Contains = False
End Function