0

i want to use a textbox to dynamically change the query

What am i doing wrong?

Set rs = conn.Execute("SELECT vfrhma000 *from vfrhma000 where maenume = textbox1.value")
FunThomas
  • 23,043
  • 3
  • 18
  • 34
  • 1
    From the line of code you have, you need to change it to `Set rs = conn.Execute("SELECT vfrhma000 *from vfrhma000 where maenume = """ & textbox1.value & """")` (assuming that the value from the textbox should be in double-quotes. – PeterT Jul 17 '19 at 13:09

1 Answers1

1

You are sending textbox1.value as search criteria. Everything within the quotes is left untouched by VBA.

If you want to get the content of the textbox, write it like this:

Set rs = conn.Execute("SELECT * from vfrhma000 where maenume = " & textbox1.value)

Now, the content of the textbox will be read by the VBA runtime and concatenated to your SQL statement.

If you are searching for a string, you will need to put (single) quotes around your search string:

Set rs = conn.Execute("SELECT * from vfrhma000 where maenume = '" & textbox1.value & "'")

In any case, you should be aware that if the textbox is used to get the search criteria from the user, you are vulnerable to SQL injection. Unless you are just playing around, you should take that serious. Have a look to https://stackoverflow.com/a/49509616/7599798 to get an idea of how to use parameters to a query.

Update If the sql statement gets more complicated, it's a good idea to write it in a variable before executing it. If it fails, you can dump the content to the immediate window, check if it looks okay and try to execute it directly against the database (new query for access, SQL*Plus or SQL developer for Oracle, SQL Management Studio for SQL Server ...)

Dim sql as string, searchValue as string
searchValue = Worksheets("sheet1").Range("e9").Value
sql = "SELECT * from vfrhma000 where maenomi = '%" & searchValue & "%'"
Debug.Print sql
Set rs = conn.Execute(searchValue)

In your case, maybe you have to change the = into a like. Also, you may want to check if cell E9 contains a valid search term.

FunThomas
  • 23,043
  • 3
  • 18
  • 34
  • this work great thank yo so much!!! Set rs = conn.Execute("SELECT * from vfrhma000 where maenume = " & textbox1.value) – Otoniel Rincon Jul 17 '19 at 13:32
  • Sorry guys. Now im wondering what if i want to reference an specific cell insted of a text box like this: Set rs = conn.Execute("SELECT em_descri,maenomi,maenomb,maeapel,maecedun, maesexo, maesuel," _ & "maefena, maefein, puetitu, ub_descri,of_descri,np_descri, cTipo_empl " _ & "from vfrhma000 where maenomi= '%" & Worksheets("sheet1").Range("e9").Value&"%'") – Otoniel Rincon Jul 18 '19 at 02:37