Opening a report with multiple criteria - vba

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

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.

How to delete rows in ms access VBA based on multiple attributes

How do I delete rows in ms access VBA based on multiple attributes?
I have written the code below, but it doesn't seem to work.
CurrentDb.Execute "DELETE * FROM StaffAtMeeting" & _
"WHERE RoomID =& Me.field1 AND MeetingDate = Me.field2 AND MeetingTime = Me.field3;"
Maybe I am missing some " (Double Quotes) and some & (Ampersands) ?
You are missing open/close " (Double Quotes) and some & (Ampersands)
currentdb.execute "DELETE * " & _
"FROM StaffAtMeeting " & _
"WHERE(((RoomID) =" & me.field1 & " AND (MeetingDate) =#" & me.field2 & "# AND (MeetingTime) =#" & me.field3 & "#));"
When you write a string statement in VBA you need an opening and closing double quotes, the ampersand acts as a concatenation. The underscore lets the code know to continue on the next line.
Since your variables are not part of the string, you have to end the string, concatenate the variable, then reopen the string. The # (pound sign/hash tag/Number sign) signifies SQL you are using a date or time.

Access Query SQL Type mismatch error when trying to update query via VBA

I have a query that takes multiple criteria from comboboxes on a form.
In order to alter the sort of the query for reporting purposes I use the below code:
Dim oDB As Database
Dim oQuery As QueryDef
Set oDB = CurrentDb
Set oQuery = oDB.QueryDefs("qry_AdjustmentDataSplitGroup")
oQuery.SQL = ("SELECT tbl_AdjustmentData.POLICY, tbl_AdjustmentData.MD, tbl_AdjustmentData.[EFF DTE], tbl_AdjustmentData.NAME, tbl_AdjustmentData.[DEP/PREM], tbl_AdjustmentData.[LST PREM], tbl_AdjustmentData.GROUP, tbl_AdjustmentData.[WA DATE] FROM tbl_AdjustmentData WHERE (((tbl_AdjustmentData.Group) Is Not Null)) ORDER BY tbl_AdjustmentData.[WA DATE];")
Set oQuery = Nothing
Set oDB = Nothing
And change the ORDER BY depending on what button is pressed on the form. This works OK.
However, I thought it would be the same if I needed to alter the query criteria (or the WHERE) I just change that line like I can change the ORDER BY part of the code.
When I use the below code for a different query:
Dim oDB As Database
Dim oQuery As QueryDef
Set oDB = CurrentDb
Set oQuery = oDB.QueryDefs("qry_AdjustmentDataSplitNonGroupApr")
oQuery.SQL = ("SELECT qry_AdjustmentDataSplitNonGroup.POLICY, qry_AdjustmentDataSplitNonGroup.MD, qry_AdjustmentDataSplitNonGroup.[EFF DTE], qry_AdjustmentDataSplitNonGroup.NAME, qry_AdjustmentDataSplitNonGroup.[DEP/PREM], qry_AdjustmentDataSplitNonGroup.[LST PREM], qry_AdjustmentDataSplitNonGroup.[WA DATE], Right([EFF DTE],2) & " / " & Mid([EFF DTE],5,2) & " / " & Left([EFF DTE],4) AS EffectiveDate, Right([WA DATE],2) & " / " & Mid([WA DATE],5,2) & " / " & Left([WA DATE],4) AS WADate, Left([EFF DTE],4) AS [Year], Left([WA DATE],4) AS WAYear FROM qry_AdjustmentDataSplitNonGroup WHERE (((Left([EFF DTE],4))=[Forms]![frm_Index]![cbo_YearPicker]) AND ((Left([WA DATE],4))=[Forms]![frm_Index]![cbo_WAPicker]) AND ((Mid([EFF DTE],5,2))=""04""));")
Set oQuery = Nothing
Set oDB = Nothing
I want to be able to remove this part:
AND ((Left([WA DATE],4))=[Forms]![frm_Index]![cbo_WAPicker])
Using an option button on the form, leaving the rest the same.
The problem though, is when I try this I get a 'Type mismatch' error on the line beginning oQuery.SQL.
I assume it's to do with the section where Mid([EFF DTE],5,2))=""04"" and I've tried double quotes as in this case, I've tried single quotes and I've tried no quotes at all changing the record in the Table from Text to Number, but always get the same error.
Is there an easier way to do this? Or can my code be ammended to work correctly?
Final note, the reason for the option button at all is to remove the 'WA Date' criteria from the query as that criteria reads from a combobox and when I fiddled with the combobox to allow an ALL option it actually returned no results.
I've heard that UNION ALL might be another way round this problem so as to avoid having to mess about removing the criteria altogether but I'm not sure how to implement that.
The situation you're facing is easy to misinterpret.
In your second code sample, you get a "type mismatch" error at the line similar to this abbreviated version:
oQuery.SQL = ("SELECT qry_AdjustmentDataSplitN ... ")
You might think that is Access complaining that your SELECT statement is not valid. But the actual problem is similar to this example from the Immediate window, which also throws a "type mismatch" error:
? "a" / "b"
That happens because you can't divide one string by another string. Division only makes sense with numerical values.
When you examine your code with that issue in mind, you should find multiple cases of this pattern:
"some text & " / " & more text"
Compare that to my "a" / "b" example.
You need to quote it differently. I will take a stab at what I think you want. I'm unsure whether the statement logic is correct, but at least this produces a valid VBA string:
Dim strSelect As String
strSelect = "SELECT q.POLICY, q.MD, q.[EFF DTE], q.NAME, " & _
"q.[DEP/PREM], q.[LST PREM], q.[WA DATE], " & _
"(Right([EFF DTE],2) & '/' & Mid([EFF DTE],5,2) & '/' & Left([EFF DTE],4)) AS EffectiveDate, " & _
"(Right([WA DATE],2) & '/' & Mid([WA DATE],5,2) & '/' & Left([WA DATE],4)) AS WADate, " & _
"Left([EFF DTE],4) AS [Year], Left([WA DATE],4) AS WAYear" & vbCrLf & _
"FROM qry_AdjustmentDataSplitNonGroup AS q" & vbCrLf & _
"WHERE Left([EFF DTE],4)=[Forms]![frm_Index]![cbo_YearPicker]" & vbCrlf & _
"AND Mid([EFF DTE],5,2)='04';"
Debug.Print strSelect ' <-- view the completed statement text in Immediate window
' Ctrl+g will take you there
oQuery.SQL = strSelect
And finally, reading between the lines, I'm guessing your EFF DTE and WA DATE values are dates as text in yyyy/mm/dd format and you want the query to display them in dd/mm/yyyy format. If that is true, compare these two expressions which should both return the same string:
Right([EFF DTE], 2) & '/' & Mid([EFF DTE], 5, 2) & '/' & Left([EFF DTE], 4)
Format([EFF DTE], 'dd/mm/yyyy')

datatype mismatch in criteria expression in MS Access

I am creating form in access in which i have to implement cascading combo boxes , data in lower combo box is dependent on its parent value selected by user. Here is form
on left side is structure of the table and on right side is form. Problem is I am getting error of data type mismatch , unable to understand why this is happening. In the afterupdate event of Diametre of Drill I am populating cutting speed . Whenever I press drop down of Cutting Speed "Datatype mismatch in criteria expression" occurs. Here is code of afterupdate event of Diametre of Drill
Private Sub cboDiameterDrilling_AfterUpdate()
cboCuttingSpeedDrilling.RowSource = "Select DISTINCT tblDrilling.cuttingSpeed " & _
"FROM tblDrilling " & _
`"WHERE tblDrilling.materials = '" & cboMaterialDrilling.Value & "' AND tblDrilling.diaOfDrill = '` `cboDiameterDrilling.Value ' " & _`
"ORDER BY tblDrilling.cuttingSpeed;"
End Sub
I think problem is in WHERE Clause . Any help would be greatly appreciated. Thank you
You've surrounded the reference to the object's value (cboDiameterDrilling.Value ) in single quotes.
AND tblDrilling.diaOfDrill = ' & cboDiameterDrilling.Value & "'"
Solution : AND tblDrilling.diaOfDrill = " & cboDiameterDrilling.Value & " " & _
I think you missed a ". Try:
Private Sub cboDiameterDrilling_AfterUpdate()
cboCuttingSpeedDrilling.RowSource = "Select DISTINCT tblDrilling.cuttingSpeed " & _
"FROM tblDrilling " & _
`"WHERE tblDrilling.materials = '" & cboMaterialDrilling.Value & "' AND tblDrilling.diaOfDrill = '" & cboDiameterDrilling.Value & "' " & _
"ORDER BY tblDrilling.cuttingSpeed;"
End Sub

DLookup ControlSource

Summary:
I want to display a value (in a text box) stored in another form upon choosing specific values from combo boxes.
I want to pass the two combo box values I have into the DLoopup property but every time I do so it gives me an error.
Below is the code is inserted in the control source property of a text box:
=DLookUp("[Year_ended]","1_Supportive_Housing","[BudgetYear] ='" & [Combo5] & "'")
This gives me an "#Error" in the text box.
Also tried the following but gives me "#NAME" error:
=DLookUp("[Year_ended]","1_Supportive_Housing","[BudgetYear] = '" & [Combo5.Value] & " And [Program_Name] = '" & [Combo7.Value] & "'")
You need to get your delimiters sorted out. AFAIR Budget Year is a number:
=DLookUp("[Year_ended]","1_Supportive_Housing","[BudgetYear] =" & [Combo5])
When you are passing a value to a numeric type field, you do not use delimiters, for text, you use quotes, either 'Abc' or "Abc", for dates, use hash (#) #2012/11/31#.
=DLookUp("[Year_ended]","1_Supportive_Housing","[BudgetYear] =" & [Combo5] & " And [Program_Name] = '" & [Combo7.Value] & "'")