Access VBA - FindFirst can't find a code that really exists - vba

The first one is supposed to be able to find all the codes that have at least the string written in the control, but it does not work at all.
The second one works fine, but only search for the specific string and that's all.
I think this is just a problem of misspelling and thats all but I cant find the way after several hours. Any help?
lentes.FindFirst "codigo = '" & "*" & Me!LenD & "*" & "' and active = true and tipo = 'montes'"
lentes.FindFirst "codigo = '" & Me!LenD & "'" & " and active = true" & " and tipo = 'montes'"

This line:
lentes.FindFirst "codigo = '*" & Me!LenD & "*' and active = true and tipo = 'montes'"
Should probably be something like this:
lentes.FindFirst "codigo LIKE '*" & Me!LenD & "*' and active = true and tipo = 'montes'"
Otherwise you're looking for a value that literally has an asterix at the beginning and end. Using LIKE means that it'll search for a pattern, not a literal value.

When you use wildcards (first expression) you are not checking equality: therefore instead of = you need to use LIKE.

Related

I am trying to lookup if a record already exist in a table

I am trying to see if a record already exist for a patient's permanent address. I tried the folowing code but it's giving me error as Data type mismatch in criteria expression matched . The AddressType is a textbox and ClientCategory is a Number. I have put the code onload event of the mainform:
If Not IsNull(DLookup("ID", "TableAddresses", "ID = '" & Me.PatientID & "' And AddressType = '" & "Permanent" & "' And ClientCategory = '" & Me.ClientCategory & "'")) Then
Me!FrmClienPatientAddressViewsubform.Form!SameAsLocal.Value = True
Else
Me!FrmClienPatientAddressViewsubform.Form!SameAsLocal.Value = False
End If
Something seems wrong here.
ID normally is a unique key, thus this should be the only value needed to look up the record:
If Not IsNull(DLookup("ID", "TableAddresses", "ID = " & Me.PatientID & "")) Then
Me!FrmClienPatientAddressViewsubform.Form!SameAsLocal.Value = True
Else
Me!FrmClienPatientAddressViewsubform.Form!SameAsLocal.Value = False
End If
Generally, the rule is: Strings within apostrophes, Integers without apostrophes.
If Gustavs solution isn't the right one and you need the other parameters, the solution could be:
Me!FrmClienPatientAddressViewsubform.Form!SameAsLocal.Value = _
Not IsNull(DLookup("ID", "TableAddresses", "ID = " & Me.PatientID & _
" And AddressType = 'Permanent' And ClientCategory = " & Me.ClientCategory))

Opening a report with multiple criteria

Can someone please guide me on this? When I use:
If Not IsNull(Me.filterLocation) And Not IsNull(Me.filterArea) Then
If Application.CurrentProject.AllReports("rptFiltered").IsLoaded =
False Then
DoCmd.OpenReport "rptFiltered", acViewPreview, , (("ColumnLocation =
'" & Me.filterLocation.Value & "'") And ("ColunmArea = '" &
Me.filterArea.Value & "'"))
Exit Sub
End If
I get a syntax error with the code above. It works if I remove:
And ("ColunmArea = '" & Me.filterArea.Value & "'"))
But I also need records with this column values to also show on the report.
There are a few issues with your code:
If a single expression traverses onto a new line, you will need to suffix the preceding line with a line continuation symbol, which, in VBA, is the underscore character (_) e.g.:
DoCmd.OpenReport "YourReport", _
acViewNormal
The and should be included in the where condition:
DoCmd.OpenReport "rptFiltered", acViewPreview, , _
"ColumnLocation = '" & Me.filterLocation.Value & "' AND ColumnArea = '" & Me.filterArea.Value & "'"
You can use the syntax highlighting of any code editor to help you to determine the elements of the code which form a string, and which lie outside of the string.
You have a typo in the name of one of your fields:
ColunmArea
' ^---------- I'm guessing this should be ColumnArea
Finally, the parentheses surrounding the where condition argument are not recommended (except when you want to force an argument to be passed by value).

Item.Restrict Function doesn't work when using like instead of =

I'm creating a macro that pulls e-mail attachments into a folder to be opened and copied, which works 100% perfect when the subject name is predefined, i.e. never changes.
' this works
Set oOlInbFiltered = oOlInb.Items.Restrict("[Subject] = " & SubjectName)
However, when I try to instead restrict for a preset beginning, say every email begins with 'aaaaa', it causes an automation error with the code below:
' this doesnt
Set oOlInbFiltered = oOlInb.Items.Restrict("[Subject] like '" & PrefixName & "%'")
Any help?
Expected results: No error message, files in folder. Instead I receive
Run-time error '-2147352567 (800200009)': Automation error Exception Occurred.
Try to use the following code instead:
criteria = "#SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & Chr(34) & " like '" & PrefixName & "%'"
Set oOlInbFiltered = oOlInb.Items.Restrict(criteria)

Two combo values into sql string

I am trying to combine two combobox selected values in a sql string with the following code :
opdragplaasnommer.CommandText = "SELECT plaasnommer FROM oesskattings
WHERE plaasnaam = '" & CmbPlaasnaam.Text & "'" And aliasnaam = " '" &
CmbAliasnaam.Text & "'"
However, I think I am messing up with my quotes and double quotes. I get the following error message :
Additional information: Conversion from string "SELECT plaasnommer
FROM oesskatt" to type 'Boolean' is not valid.
You really ought to learn how to use the String.Format method or string interpolation. It is far less error-prone than using the concatenation operator (&) over and over. You can see the issue with your code simply by looking at the colour. Anything in a literal String should be red and you can see some of yours that should be red but isn't. Presumably it should be something like this:
opdragplaasnommer.CommandText = "SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '" & CmbPlaasnaam.Text & "' And aliasnaam = '" & CmbAliasnaam.Text & "'"
Using String.Format would look like this:
opdragplaasnommer.CommandText = String.Format("SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '{0}' And aliasnaam = '{1}'", CmbPlaasnaam.Text, CmbAliasnaam.Text)
As you can see, far less easy to mess up. String interpolation would look like this:
opdragplaasnommer.CommandText = $"SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '{CmbPlaasnaam.Text}' And aliasnaam = '{CmbAliasnaam.Text}'"
Given that this is SQL code, an even better idea would be to use parameters. I'm not going to go into detail about that because there's information all over the place but it's something that you really need to learn. Apart from your code being less error-prone, it will help avoid crashes due to formatting issues and, most importantly, protect you from SQL injection attacks.
You have messed up with your string;
opdragplaasnommer.CommandText = "SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '" & CmbPlaasnaam.Text & "' And aliasnaam = '" & CmbAliasnaam.Text & "'"
In VB .NET string concatination is performed with & symbol. And new line requires underscore.
opdragplaasnommer.CommandText = "SELECT plaasnommer FROM oesskattings" & _
" WHERE plaasnaam = '" & CmbPlaasnaam.Text & "' And aliasnaam = '" & _
CmbAliasnaam.Text & "'"
But I would suggest to use String.Format function in this case.
opdragplaasnommer.CommandText = String.Format("SELECT plaasnommer FROM oesskattings WHERE plaasnaam = '{0}' and aliasnaam = '{1}'",
CmbPlaasnaam.Text,CmbAliasnaam.Text)
And again this just another way. But, to say the truth, I hate concatination for SQL queries. Better to declare SQL Parameters and assign value to them.

SQL Variable in Where Clause

Dim varCity As String
varCity = Me.txtDestinationCity
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE" & Me.txtDestinationCity & "= [TDestinationType].[tPreTravelDestinationCity]"
I am trying to select the states for the selected city. There is a drop down box with a list of cities. That box is titled txtDestinationCity.
It says I have an error in my FROM clause.
Thank you
You miss a space and some quotes. How about:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE '" & Me.txtDestinationCity & "' = [TDestinationType].[tPreTravelDestinationCity]"
Copy that next to your original to see the difference.
And for reasons SQL, PLEASE reverse the comparison. Always mention the column left and the value right:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = '" & Me.txtDestinationCity & "'"
Since the quotes are annoying and easy to miss, i suggest defining a function like this:
Public Function q(ByVal s As String) As String
q = "'" & s & "'"
End Function
and then write the SQL string like that:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(Me.txtDestinationCity)
This makes sure you ALWAYS get both quotes at the right places and not get confused by double-single-double quote sequences.
If you care about SQL-injection (yes, look that up), please use the minimum
Public Function escapeSQL(sql As String) As String
escapeSQL = Replace(sql, "'", "''")
End Function
and use it in all places where you concatenate user-input to SQL-clauses, like this:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(escapeSQL(Me.txtDestinationCity))
Lastly, breakt it for readability. I doubt your editor shows 200 characters wide:
Me.txtDestinationState.RowSource = _
"SELECT tPreTravelDestinationState " & _
"FROM [TDestinationType] " & _
"WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(escapeSQL(Me.txtDestinationCity))
Note the trailing spaces in each line! Without them, the concatenation will not work.
It can be easier to troubleshoot your query construction if you set it to a variable (e.g., strSQL) first. Then you can put a breakpoint and see it right before it executes.
You need a space after WHERE. Change WHERE" to WHERE<space>"
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE " & Me.txtDestinationCity & "= [TDestinationType].[tPreTravelDestinationCity]"