Results 1 to 5 of 5
  1. #1
    Join Date
    May 2011
    Posts
    4

    Unanswered: Referencing table field names as a variable

    The basics of the problem are this: I have a form with 1 combo box (searchfield) and one text box (searchfor). The combo box is populated with all of the field names from the table tblPeople. The idea is that the user can select which field name they want to add to a query (qrySearch) and apply a filter to that field using the text box (searchfor). My code, listed below, works beautifully as long as I manually enter the searchfield (in this case Title) in both the SELECT and WHERE statement. How can I use a variable to automatically insert the searchfield value for me?



    Private Sub Search_Click()


    Dim qdf As QueryDef
    Set qdf = CurrentDb.QueryDefs("qrySearch")

    qdf.SQL = "SELECT [Full Name], [Residence],[Title] From tblPeople WHERE Title= Forms!frmSearch!searchfor"


    DoCmd.OpenQuery "qrySearch"


    End Sub

  2. #2
    Join Date
    Mar 2009
    Posts
    5,442
    Provided Answers: 14
    Code:
    Dim strFieldName as String
    strFieldName = Me.searchfield.Value
    qdf.SQL = Replace("SELECT [Full Name], [Residence],[@Field] From tblPeople WHERE @Field= Forms!frmSearch!searchfor", "@Field", strFieldName)
    Do not forget that if the concerned field is of type Text the value should be enclosed in single quotes.
    Have a nice day!

  3. #3
    Join Date
    May 2011
    Posts
    4
    PERFECT!!! Thank you so much!!!!!!

  4. #4
    Join Date
    Feb 2004
    Location
    New Zealand
    Posts
    1,423
    Provided Answers: 8
    Theway i do it

    is write the SQL in Full use the [] and replace function

    only becasuse it look beater to read. when looking at the code

    SQL = "SELECT [Full Name], [Residence],[Title] From tblPeople WHERE [Title]='[CRIT]'"

    SQL =replace(SQL,"[Title]",me.title)
    SQL = replace(SQL,"[CRIT]",me.searchfor)
    hope this help

    See clear as mud


    StePhan McKillen
    the aim is store once, not store multiple times
    Remember... Optimize 'til you die!
    Progaming environment:
    Access based on my own environment: DAO3.6/A97/A2000/A2003/A2007/A2010
    VB based on my own environment: vb6 sp5
    ASP based on my own environment: 5.6
    VB-NET based on my own environment started 2007
    SQL-2005 based on my own environment started 2008
    MYLE
    YOUR PASSWORD IS JUST LIKE YOUR TOOTHBRUSH DON'T SHARE IT.

  5. #5
    Join Date
    Mar 2009
    Posts
    5,442
    Provided Answers: 14
    You're welcome!
    Have a nice day!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •