MS Access – VBA – Determine in Which Table a Field is Located

This was the question put forth by someone on an Access Forum recently and I thought I’d share one possible way to determine this.

This is a brute force method, but it works! I simply loop through all the tables one by one and loop through all the fields within each table one by one. It is that simple. Here is the code.

'---------------------------------------------------------------------------------------
' Procedure : WhereFieldLocated
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Determine/Locate in which Table(s) a field is located
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFieldName: The name of the field you are trying to locate
'
' Usage:
' ~~~~~~
' WhereFieldLocated "Filed1"
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2011-Aug-17                 Initial Release
'---------------------------------------------------------------------------------------
Function WhereFieldLocated(sFieldName As String)
    Dim db            As DAO.Database
    Dim td            As DAO.TableDefs
    Dim fld           As DAO.Field

    Set db = CurrentDb()
    Set td = db.TableDefs
    For Each t In td    'loop through all the tables in the database
        If Left(t.Name, 4) = "MSys" Then GoTo Continue
        For Each fld In t.Fields    'loop through all the fields of the table
            If fld.Name = sFieldName Then
                Debug.Print t.Name
            End If
        Next
Continue:
    Next

    Set fld = Nothing
    Set td = Nothing
    Set db = Nothing
End Function

One response on “MS Access – VBA – Determine in Which Table a Field is Located

  1. mike

    So you looping throuth all tables to find column name. it would be use to build qryies on the fly so first you list all tables in list box then build event to get colums for selected table
    Nice thanks for idea