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

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))

Related

Looping through table to find value from a textbox

I'm trying to loop through a column inside a table from a form in Access to find out whether a "Case Name" already exists or not, and if it does not, then add the new record to the table. I want the criteria to be based on the input value of a text box. The good news is I have figured out how to add a new record to the table with the code below. I'm just stuck on how to loop through a table to find out if a record already exists. Thanks in advance!
Private Sub SaveNewCase_Click()
If Me.txtNewCaseName.Value <> "Null" And Me.txtCaseDepth.Value <> "Null" And Me.txtCaseHeight2.Value <> "Null" And Me.txtCaseWeight.Value <> "Null" And Me.txtCaseWidth <> "Null" And Me.cboCaseCategory.Value <> "Null" Then
'I think the loop should go here, but not sure'
CurrentDb.Execute "INSERT INTO tblCases(CaseName, CaseWidth, CaseHeight, CaseCasters, CaseWeight, CaseDepth, CaseCategory) " & _
" VALUES ('" & Me.txtNewCaseName & "'," & Me.txtCaseWidth & "," & Me.txtCaseHeight2 & ",'" & Me.chkboxCasters & "'," & Me.txtCaseWeight & "," & Me.txtCaseDepth & ",'" & Me.cboCaseCategory & "')"
Else
MsgBox "Please enter all new case criteria."
End If
End Sub
Firstly, use parameters!
Concatenating values supplied by a user directly into your SQL statement exposes your to SQL injection, either intentional (i.e. users entering their own SQL statements to sabotage your database) or unintentional (e.g. users entering values containing apostrophes or other SQL delimiters).
Instead, represent each of the field values with a parameter, for example:
With CurrentDb.CreateQueryDef _
( _
"", _
"insert into " & _
"tblcases (casename, casewidth, caseheight, casecasters, caseweight, casedepth, casecategory) " & _
"values (#casename, #casewidth, #caseheight, #casecasters, #caseweight, #casedepth, #casecategory) " _
)
.Parameters("#casename") = txtNewCaseName
.Parameters("#casewidth") = txtCaseWidth
.Parameters("#caseheight") = txtCaseHeight2
.Parameters("#casecasters") = chkboxCasters
.Parameters("#caseweight") = txtCaseWeight
.Parameters("#casedepth") = txtCaseDepth
.Parameters("#casecategory") = cboCaseCategory
.Execute
End With
Since the value of each form control is fed directly to the parameter within the SQL statement, the value will always be interpreted as a literal and cannot form part of the SQL statement itself.
Furthermore, you don't have to worry about surrounding your string values with single or double quotes, and you don't have to worry about formatting date values - the data is used in its native form.
Where testing for an existing value is concerned, you can either use a domain aggregate function, such as DLookup, or you could use a SQL select statement and test that no records are returned, e.g.:
Dim flg As Boolean
With CurrentDb.CreateQueryDef _
( _
"", _
"select * from tblcases where " & _
"casename = #casename and " & _
"casewidth = #casewidth and " & _
"caseheight = #caseheight and " & _
"casecasters = #casecasters and " & _
"caseweight = #caseweight and " & _
"casedepth = #casedepth and " & _
"casecategory = #casecategory " _
)
.Parameters("#casename") = txtNewCaseName
.Parameters("#casewidth") = txtCaseWidth
.Parameters("#caseheight") = txtCaseHeight2
.Parameters("#casecasters") = chkboxCasters
.Parameters("#caseweight") = txtCaseWeight
.Parameters("#casedepth") = txtCaseDepth
.Parameters("#casecategory") = cboCaseCategory
With .OpenRecordset
flg = .EOF
.Close
End With
End With
If flg Then
' Add new record
Else
' Record already exists
End If
Finally, you're currently testing the values of your form controls against the literal string "Null", which will only be validated if the user has entered the value Null into the control, not if the control is blank.
Instead, you should use the VBA IsNull function to check whether a variable holds a Null value.

VBA bad syntax in dlookup function with global variables

I am using 8 similar functions in my code and they all work, but this one is not working:
global_var_13=DLookup("[amount]", "[tabla amortizacion real]","[no contract]= get_global('global_var_10') and [ident]=get_global('global_var_11') and [cuota]= get_global('global_var_12')")
var_10 is a string, var_11, var_12, and var_13 are numeric.
The values are var_10= "GAF-27/2013", var_11=1, var_12=1
global_var_13 is returning NULL
Any thoughts about the syntax?
Try to concatenate the clause elements:
global_var_13 = DLookup("[amount]", "[tabla amortizacion real]", "[no contract] = '" & get_global("global_var_10") & "' and [ident] = " & get_global("global_var_11") & " and [cuota] = " & get_global("global_var_12") & "")

Access Update QueryDef Parameters not found

I've two queries I'm trying to create with QueryDef.
This insert query works perfectly and I can assign the parameters:
Dim qryAddPackage As String: qryAddPackage = "" & _
"INSERT INTO `RMF_tblPackages` " & _
"(`SystemID`, `DoD`, `DateCreated`, `LastModified`, `LastUpdatedBy`) " & _
"VALUES ([SystemID], [DoD], NOW(), NOW(), [UID])"
With CurrentDb.CreateQueryDef(vbNullString, qryAddPackage)
.Parameters!SystemID.Value = cbbSystems.Value
.Parameters!DoD.Value = Me.txtDoD.Value
.Parameters!UID.Value = strGetUserID()
.Execute
End With
However, in this update query, I am only able to access the Parameter UID in the WHERE statement:
Dim qryUpdatePkg As String: qryUpdatePkg = "" & _
"UPDATE `RMF_tblPackages` " & _
"SET " & _
"`SystemID` = [SystemID], `DoD` = [DoD], `LastModified` = NOW(), `LastUpdatedBy` = [UID] " & _
" WHERE `PackageID` = [PackageID]"
With CurrentDb.CreateQueryDef(vbNullString, qryUpdatePkg)
.Parameters("SystemID").Value = cbbSystems.Value
.Parameters!DoD.Value = Me.txtDoD.Value
.Parameters!UID.Value = strGetUserID()
.Parameters!PackageID.Value = Me.lbxPackages.Value
.Execute dbSeeChanges
End With
In every other line trying to assign a parameter, it just says that the parameter's name is not in the collection.
I've tried assigning them like this:
.Parameters("PackageID").Value = Me.lbxPackages.Value
As well, but that doesn't work either.
I tried just running the update query with some data and it worked fine so the query works.
.Params.count returns 1 as you would expect given it's only recognizing one param.
Any other ideas as to why the parameters aren't being recognized by that update query?
Use [ ] for quoting identifiers. In Access the backtick is not valid (unlike MySQL). Also column names and parameter names use the same quoting characters, so you must choose different names for the parameters. Quoting identifiers is only necessary if the names collide with a reserved word or function name (like Date, From, By, Order etc).
Dim qryUpdatePkg As String
qryUpdatePkg = "UPDATE RMF_tblPackages " & _
"SET " & _
"SystemID = prmSystemID, DoD = prmDoD, LastModified = Now(), LastUpdatedBy = prmUID " & _
" WHERE PackageID = prmPackageID"
With CurrentDb.CreateQueryDef(vbNullString, qryUpdatePkg)
.Parameters("prmSystemID").Value = cbbSystems.Value
.Parameters!prmDoD.Value = Me.txtDoD.Value
.Parameters!prmUID.Value = strGetUserID()
.Parameters!prmPackageID.Value = Me.lbxPackages.Value
.Execute dbSeeChanges
End With
Do the same changes in the first query.

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

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.

Run Time error 3061 Too Few parameters. Expected 6. Unable to update table from listbox

All,
I am running the below SQL and I keep getting error 3061. Thank you all for the wonderful help! I've been trying to teach myself and I am 10 days in and oh my I am in for a treat!
Private Sub b_Update_Click()
Dim db As DAO.Database
Set db = CurrentDb
strSQL = "UPDATE Main" _
& " SET t_Name = Me.txt_Name, t_Date = Me.txt_Date, t_ContactID = Me.txt_Contact, t_Score = Me.txt_Score, t_Comments = Me.txt_Comments" _
& " WHERE RecordID = Me.lbl_RecordID.Caption"
CurrentDb.Execute strSQL
I am not sure but, you can try somethink like that
if you knom the new value to insert in the database try with a syntax like this one
UPDATE table
SET Users.name = 'NewName',
Users.address = 'MyNewAdresse'
WHERE Users.id_User = 10;
Now, if you want to use a form (php)
You have to use this
if(isset($_REQUEST["id_user" ])) {$id_user = $_REQUEST["id_user" ];}
else {$id_user = "" ;}
if(isset($_REQUEST["name" ])) {$name= $_REQUEST["name" ];}
else {$name = "" ;}
if(isset($_REQUEST["address" ])) {$address= $_REQUEST["adress" ];}
else {$adress= "" ;}
if you use mysql
UPDATE table
SET Users.name = '$name',
Users.address = '$adress'
WHERE Users.id_User = 10;
i don't know VBA but I will try to help you
Going on from my comment, you first need to declare strSQL as a string variable.
Where your error expects 6 values and access doesn't know what they are. This is because form objects need to be outside the quotations of the SQL query, otherwise (as in this case) it will think they are variables and obviously undefined. The 6 expected are the 5 form fields plus 'strSQL'.
Private Sub b_Update_Click()
Dim db As DAO.Database
dim strSQL as string
Set db = CurrentDb
strSQL = "UPDATE Main" & _
" SET t_Name = '" & Me.txt_Name & "'," & _
" t_Date =#" & Me.txt_Date & "#," & _
" t_ContactID =" & Me.txt_Contact & "," & _
" t_Score =" & Me.txt_Score & "," & _
" t_Comments = '" & Me.txt_Comments & "'," & _
" WHERE RecordID = '" & Me.lbl_RecordID.Caption & "';"
CurrentDb.Execute strSQL
end sub
Note how I have used double quotes to put the form fields outside of the query string so access knows they aren't variables.
If your field is a string, it needs encapsulating in single quotes like so 'string'. If you have a date field it needs encapsulating in number signs like so #date# and numbers/integers don't need encapsulating.
Look at the code I have done and you can see I have used these single quotes and number signs to encapsulate certain fields. I guessed based on the names of the fields like ID's as numbers. I may have got some wrong so alter where applicable... Or comment and I will correct my answer.