how to run SQL query with VBA

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • questionit
    Contributor
    • Feb 2007
    • 553

    how to run SQL query with VBA

    I havea combo box. If i select any value , i want to do the following.

    Run a sql query that would fetch a value from a table

    For example:
    If Combo2.Value = "1"

    getResult = Run sql query
  • JKing
    Recognized Expert Top Contributor
    • Jun 2007
    • 1206

    #2
    You can use the DLookup function.

    [code=vb]
    getResult = DLookup("[fieldName]", "YourTable" , "[fieldID] = " & Me.ComboBox1)
    [/code]

    Comment

    • questionit
      Contributor
      • Feb 2007
      • 553

      #3
      Hi

      i am getting runtime error: First of all, in code line below, can you tell me what does fieldID do - i mean is it refering to field in the table - same as the fieldName? "list" is name of my table

      getResult = DLookup("[fieldName]", "list", "[fieldID] = " & Me.Combo0)

      please clarify


      Originally posted by JKing
      You can use the DLookup function.

      [code=vb]
      getResult = DLookup("[fieldName]", "YourTable" , "[fieldID] = " & Me.ComboBox1)
      [/code]

      Comment

      • JKing
        Recognized Expert Top Contributor
        • Jun 2007
        • 1206

        #4
        fieldName is the value you want to look up and fieldID would be the primary key for that row. The third parameter acts as your where criteria so you're not limited to only searching on primary keys.

        Let's say I have a table called tblFruit.
        In that table is the following
        fruitID------fruitName------fruitColor
        ....1.......... .......Apple... .............Re d
        ....2.......... ......Orange... .........Orange
        ....3.......... ......Banana... .........Yellow

        [code=vb]
        getResult = Dlookup("[fruitName]", "tblFruit", "[fruitID] = " & Combo0)
        [/code]

        If Combo0 = 1 getResult would be "Apple"

        For more examples or a more indepth look at Dlookup just open up Visual Basic Help. To do this you simply put the cursor on the word Dlookup in your code and hit F1 to bring up the helpfile for that keyword.

        Comment

        • abolos
          New Member
          • Apr 2007
          • 65

          #5
          Originally posted by questionit
          I havea combo box. If i select any value , i want to do the following.

          Run a sql query that would fetch a value from a table

          For example:
          If Combo2.Value = "1"

          getResult = Run sql query

          You may use:
          Form.RecordSour ce = "select stname from tblnameage where stage = " & Combo0.value
          Me.Requery

          But first open the form in a design mode and put in Data | Record Source: SELECT [tblNameAge].[stName], [tblNameAge].[stAge] FROM tblNameAge;

          Comment

          Working...