VBA LIKE operator with string - vba

I have this code:
Private Sub Item_AfterUpdate()
Me.SApp.Form.RecordSource = "SELECT * FROM Application WHERE Item = '" & Me.Item.Value & "';"
End Sub
Now , this works so it filters SApp (a subform) base on the value in the combobox Item.
I wanna do something similar however not with equal but with like.
So , something like:
Private Sub Item_AfterUpdate()
Me.SApp.Form.RecordSource = "SELECT * FROM Application WHERE Item LIKE '" & Me.Item.Value & "';"
End Sub
I tried :
'% Me.Item.Value %'
'% '" & Me.Item.Value & "' %'
'% s %' with (Dim s as string ; s = Me.Item.Value)
None of this solutions works , any idea on how to fix this?

Use the * wildcard in MsAccess, in other dbs it's usually %.
Ref: https://msdn.microsoft.com/en-us/library/bb208897(v=office.12).aspx

Related

VBA WildCard in Excel List Objects

I have a list object loaded and I'm trying to filter it with the code below.
If I use a fixed SQL statement below the code works as expected.
SELECT * FROM [All Contracts] WHERE [Asset_Number] = "Q123456"
However trying to bring in any form of wildcard to the search string results in a 1004 error.
Here is the current sub in question:
Public Sub QueryData( _
ByVal form As Variant _
)
Dim ws As Worksheet
Set ws = form.Worksheet
Dim searchTxt As String
Let searchTxt = form.textBox_FirstAssetNumber.value
' Build the SQL Statment
Dim SQL As String
If searchTxt = vbNullString Then
Let SQL = "Array(SELECT * FROM [All_Contracts])"
Else
Let SQL = "SELECT * FROM [All Contracts] WHERE (((Asset_Number) Like %" & [searchTxt] & "%));"
End If
#If Testing = 1 Then
Debug.Print "SQL Satatment is: " & SQL
#End If
With ws.ListObjects.item(1).QueryTable
.CommandType = xlCmdSql
.CommandText = SQL
.Refresh
End With
End Sub
I have tried replacing 'Like' with Where, also '*' with '%' added brackets, removed brackets all seem to result in a 104 error.
The code and SQL work if I do not use the wildcard in the query.
What am I missing?
The wildcards and the text you are searching for should be within quotes.
SQL = "SELECT * FROM [All Contracts] WHERE Asset_Number Like '%" & searchTxt & "%';"
SQL = "Select * FROM [All Contracts$] WHERE [Asset_Number] LIKE '%" & searchTxt & "%'"
"All Contracts" is a Sheet tab?

visual basic like error

Private Sub txtmid_Change()
On Error Resume Next
Mmid = txtmid.Text
Adodc1.RecordSource = "select * from members where txtmid like '" & Mmid & "'"
Adodc1.Refresh
Mname = Adodc1.Recordset.Fields("Mname").Value
Expiryd = Adodc1.Recordset.Fields("Expiryd").Value
txtname.Text = Mname
txtedate(1).Text = Format(Expiryd, "dd / mm / yyyy")
End Sub
I am getting FROM clause error. Please help me to resolve this error. Thank you.
Try this:
First of all, remove On Error Resume Next, because it's dangerous (you should use a very error handler, instead).
Adodc1.RecordSource = "select * from members where Mmid = '" & Mmid & "'"
Note: anyway, for fields of TEXT type, you should use always Replace$() to 'double quote' to avoid mistake when string values contains a single quote. Example:
Dim sql As String
Dim sSearch As String
sSearch = "You are 'magic' developer"
sql = "SELECT * FROM Users WHERE Note = '" & Replace$(sSearch, "'", "''") & "'"
Otherwise, in this case, if you use (wrongly):
sql = "SELECT * FROM Users WHERE Note = '" & sSearch & "'"
You will get a error.

Filter datasource where column like/contains VB.NET

UPDATE
Thanks to Hanlet the problem is solved, the syntax is like so:
source1.Filter = "[Column] LIKE '%" & TextBox1.Text & "%'"
Also for anyone interested, this is the syntax for performing the above on multiple criteria:
source1.Filter = "[Column1] LIKE '%" & TextBox1.Text & "%' OR [Column2] LIKE '%" & TextBox1.Text & "%'"
I currently have code to filter my datasource where the column 'Customer Name' equals the text in the text box.
However, what I want is a filter that is similar to the LIKE function in sql, so if the customer name is 'John' and the user inputs 'Jo' into the text box, it will filter all customers who's name is LIKE/contains 'Jo'
This is the current filter code (if you want the code showing how the data is bound just ask):
Dim source1 As New BindingSource()
source1.Filter = "[Customer Name] = '" & TextBox1.Text & "'"
dTableMain.Refresh()
Thanks for any help!
I've done something similar in the past. Here's the general syntax:
' The searchString is searched for in both the Cost Center field AND the Code field
BindingSource.Filter = "[col1] like " & searchString & " OR [col2] like " & searchString
In your case, it would be:
source1.Filter = "[Customer Name] like " & TextBox1.Text
Hope it helps!

SQL/VB.NET Search-Function looking for at least one correct input

I'm writing a program in Visual Basic about Databases. Now I have a Sub/Function who searches the database for correct inputs. I have five text boxes where the user can put in something for each data field.
If txtBox1.Text <> "" Or txtBox2.Text <> "" Or txtBox3.Text <> "" Or txtBox4.Text <> "" Or txtBox5.Text <> "" Then
Try
connection.Open()
command.CommandText = "SELECT * from lager WHERE (lager_waren_id LIKE '" & txtBox1.Text & "' OR lager_warenanzahl LIKE '" & txtBox2.Text & "' OR lager_warenname LIKE '%" & txtBox3.Text & "%' OR lager_warengewicht LIKE '" & txtBox4.Text & "%' OR lager_waren_verkaufspreis LIKE '" & txtBox5.Text & "%');"
reader = command.ExecuteReader()
FormKunde.Enabled = True
FormKunde.lstViewKundeStore.Items.Clear()
Do While reader.Read()
Dim lstViewItem As New ListViewItem(reader("lager_waren_id").ToString())
lstViewItem.SubItems.Add(reader("lager_warenanzahl").ToString())
lstViewItem.SubItems.Add(reader("lager_warenname").ToString())
lstViewItem.SubItems.Add(reader("lager_warengewicht").ToString())
lstViewItem.SubItems.Add(reader("lager_waren_verkaufspreis").ToString())
FormKunde.lstViewKundeStore.Items.Add(lstViewItem)
Loop
reader.Close()
FormKunde.Enabled = False
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
connection.Close()
Else
MessageBox.Show("Please fill in something in the text fields")
Exit Sub
End If
I'm aksing the database if at least one text field has some input that matches to the data field it belongs to. But when I put something in, doesn't matter how much, nothing happens in my list view. It just loads all data back in the list view. When I try to do "AND" instead of "OR", it works only if i fill all text fields with the correct datas for one data set. But I want, that it finds all data sets.
An example:
I have two data sets where the names are "App" and "Apple". When i just fill in "Ap" in the field for names (nothing in the others) it shows me both. I think it should work with "OR", but it just does nothing.
I'm really confused how to solve this, I hope anyone has a guess. Thank you!
Your problem is that your query always uses all the conditions also when there is no input in the relevant textboxes. In this way your LIKEs become LIKE '%%' and, of course, this matches every record.
You need to add the conditions only if the textboxes are not empty or null.
So you need to build your query in parts after checking if the textbox contains any value to search for.
connection.Open()
Dim sql = "SELECT * from lager WHERE "
if Not string.IsNullOrWhiteSpace(textBox1.Text) Then
sql = sql & "lager_waren_id LIKE #p1 OR "
command.Parameters.AddWithValue("#p1", textBox1.Text)
End If
if Not string.IsNullOrWhiteSpace(textBox2.Text) Then
sql = sql & "lager_warenanzahl LIKE #p2 OR "
command.Parameters.AddWithValue("#p2", textBox2.Text)
End If
if Not string.IsNullOrWhiteSpace(textBox3.Text) Then
sql = sql & "lager_warenname LIKE #p3 OR "
command.Parameters.AddWithValue("#p3", "%" & textBox3.Text & "%")
End If
if Not string.IsNullOrWhiteSpace(textBox4.Text) Then
sql = sql & "lager_warengewicht LIKE #p4 OR "
command.Parameters.AddWithValue("#p4", textBox4.Text & "%")
End If
if Not string.IsNullOrWhiteSpace(textBox5.Text) Then
sql = sql & "lager_waren_verkaufspreis LIKE #p5 OR "
command.Parameters.AddWithValue("#p5", textBox5.Text & "%")
End If
' Remove the last OR if any ....'
if sql.EndsWith(" OR ") then
sql = sql.Substring(0, sql.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
if sql.EndsWith(" WHERE ") then
sql = sql.Substring(0, sql.Length - 7)
End If
command.CommandText = sql
reader = command.ExecuteReader()
Notice also that you should ALWAYS use a parameterized query to avoid Sql Injection particularly when you get your inputs directly from your user. (Not to mention the problems with typed texts that contain a single quote)
I hope I understand your problem correctly. I am sure there are better ways to do this and my VB is rusty but something like this may work
Dim query As String = "SELECT * FROM lager"
Function addField (ByVal query As String, ByVal value as String, ByVal field as String) As String
addField = query
If value <> "" Then
If query.IndexOf("where", 0, StringComparison.CurrentCultureIgnoreCase) > -1 Then
addField = query & " AND " & field & " LIKE '%" & value & "%'"
Else
addField = query & " WHERE " & field & " LIKE '%" & value & "%'"
End If
End If
End Function
query = addField(query, txtBox1.Text, "lager_waren_id")
query = addField(query, txtBox2.Text, "lager_warenanzahl")
'...continue adding fields...'
command.CommandText = query
This should make it so your query string only includes the populated fields

VBscript/SQL concatenation of %

Ok, I am new to the forum and fairly new to coding, I've searched high and low, and I understand that vbscript requires escapes or Chr() to use special characters. In the following code I need to concatenate a '%' after the "doc_no" as a wildcard for a sybase database to pull up the list of document numbers that I need to appear in my table.
I have tried
' " & doc_no " ' & Chr(37) " 'this returned that "&" is an invalid character
' " & doc_no " ' || Chr(37) "
' " & doc_no " ' + ""%"" " returned + as an invalid character
I have tried several variations of each type, and I cannot find any similar situation online. Any advice? Again, I am only 4 months into my programming life so bear with me please. Below is a snippet of the code from which the above originates.
<%
Dim document(1024)
counter = 0
cmdString = ""
cmdString = cmdString & "SELECT dbo.dsk_obj.obj_id,"
cmdString = cmdString & " docno = dbo.dsk_obj.obj_usr_num "
cmdString = cmdString & "FROM dbo.dsk_obj "
cmdString = cmdString & "WHERE dbo.dsk_obj.obj_usr_num LIKE '" & doc_no & "' I NEED TO CONCAT. % HERE "
objRS.Open cmdString, objConn, adOpenStatic, 3, adCmdText
WHILE (objRS.EOF = False)
document(counter) = objRS("docno")
counter = counter + 1
objRS.MoveNext
WEND
objRS.Close
%>
<% FOR ii = 0 TO counter -1 %>
<%=document(ii)%>
<%
NEXT
%>
the output should look something like this
1555307375-0001
1555307375-0002
1555307375-0003
Any help would be greatly appreciated! Thanks! Jeremy
First, you should avoid string concatenation because of SQL injection.
Now what you are trying to do is to create a SQL string in VBScript. The SQL you desire looks something like:
LIKE '123%'
To create this, you need a string in VBScript like:
Dim string = "LIKE '123%'"
To change out 123 for your doc number, you can do:
Dim string = "LIKE '" & doc_no & "123%'"
In your case, it would be:
cmdString = cmdString & "WHERE dbo.dsk_obj.obj_usr_num LIKE '" & doc_no & "%'"
But please don't do this. You should pass the parameter in instead of using string concatenation.