I'm having trouble getting Access to search on a multi-valued filed for a report. The multi-valued field is Group_List, and when trying to search a value in the multi-valued field and I keep getting the error that says cannot search in a where or having a clause. In the report, if I search for a value in the field I would only like those values to show up in the report.
Private Sub Command284_Click()
Dim reportsearch As String
Dim reportText As String
Dim strReport As String
If IsNull(Me.txtReport.Value) Then
strReport = "'SELECT * FROM NCECBVI'"
DoCmd.OpenReport "NCECBVI-Report", acPreview, , strReport
txtReport.Value = ""
Else
reportText = Me.txtReport.Value
reportsearch = "[Last Name] LIKE ""*" & reportText & "*"" OR [First Name] LIKE ""*" & reportText & "*"" OR Group_List LIKE "" * " & reportText & " * """
DoCmd.OpenReport "NCECBVI-Report", acPreview, , reportsearch
txtReport.Value = ""
End If
End Sub
Although I highly recommend to not use this kind of "dynamic query", there is a way to handle that kind of criteria for mutivalued fields.
Supposed that your Group_List is filled from a Groups table that as a GroupID and a GroupName column, you need to join your Groups table to the NCECBVI table (Connecting GroupID and Group_List.Value) and apply the criteria to the GroupName field. To show every record of the NCECBVI table only once, use DISTINCTROW. The assembled query would look something like this:
SELECT DISTINCTROW NCECBVI.*
FROM NCECBVI
INNER JOIN Groups ON Groups.GroupID = NCECBVI.Group_List.Value
WHERE Groups.GroupName LIKE "*SomeText*"
To deal with queries on multi-valued fields, I recommend this article.
Related
I have a command button to open a report with a filter applied by a query. This is so that I can filter the report by the value of a field in a subreport of the parent report, otherwise the filter criteria would be more straightforward.
I have set my Wherecondition as follows:
Private Sub CmdOpenReport_Click()
DoCmd.OpenReport "rptName", , , CategoryID = [Queries].[qryFltrRptByCat]!CategoryID
End Sub
When I click the button, I get the following error message:
Run-time error '2465'
Microsoft Access can't find the field referred to in your expression.
What is the proper syntax to refer to the field in the query?
The query looks for a value in the subform and finds the matching CategoryID for the subform value. This is because the data in the subform has a many-to-one relationship with the CategoryID in the parent form.
Cannot reference tables or queries directly like that. Use DLookup(). Or refer to control on form. Must concatenate variable to literal string, don't forget quote marks:
DoCmd.OpenReport "rptName", , , "CategoryID = " & Me.CategoryID
If the CategoryID is in a active form and a string you can use:
Docmd.OpenReport "rptName", , , "CategoryID = '" & Me.CategoryID & "'"
If the CategoryID is in a active form and a integer/double you can use:
Docmd.OpenReport "rptName", , , "CategoryID = " & Me.CategoryID
If the CategoryID is in the mainform but the subform is active you can use:
Docmd.OpenReport "rptName", , , "CategoryID = " & Me.Parent.CategoryID
And you always can use a total reference:
Docmd.OpenReport "rptName", , , "CategoryID = " & Forms!YourForm!CategoryID
You can look here for further informations:
Access table Allowances_3_15_18 has 5 columns. I want to insert a calculated field from a form EmployeeSalary) into one of the columns Amount in the table.
Each value will link with the relevant primary ID's from the form and the table which are the same JobID. How do I do this in VBA?
I currently have done it in the afterUpdate event in the property sheet.
Private Sub ProjectedDollarAmount_AfterUpdate()
Dim strSQL As String
Dim ProjectedDollarAmount As Currency
strSQL = "INSERT INTO [Allowances_3_15_18] ([Amount]) VALUES (" & _
PrepareSQLNumber(Me.ProjectedDollarAmount) & ") WHERE JobID = " & _
PrepareSQLNumber(Me.JobID) & ";"
Call ExecuteMyCommand(strSQL)
End Sub
You need to get away from SQL concatenation and start using parameters.
Create a query with two parameters, the amount to be inserted and the JobId. The query's SQL should be something like this:
PARAMETERS [prmAmount] Currency, [prmJobId] Long;
UPDATE [Allowances_3_15_18] SET [Amount] = [prmAmount]
WHERE JobID = [prmJobId];
Then in code, simply pass the parameter values and execute the above query:
Sub Add()
With CurrentDb().QueryDefs("qryName")
.Parameters("[prmAmount]").Value = PrepareSQLNumber(Me.ProjectedDollarAmount)
.Parameters("[prmJobId]").Value = PrepareSQLNumber(Me.JobID)
.Execute dbFailOnError
End With
End Sub
You need to change the qryName to the actual name of the query.
You can read more about parameter queries here.
I have an Access Form that lists addresses and details related to those addresses. It is filtered manually by staff using the standard menus to come down to a list of relevant addresses.
I'd like to output those filtered results to a table (temp table) so that I can use it to create mailings.
Is this possible and if so what sort of code should I be using for a button.
TIA
MK
When users filtering records, they are changing .Filter property of form. Text of this property is equivalent of WHERE clause of SQL. So, all you need is to create INSERT ... SELECT... SQL query with the same source as record source of form and use filter text for WHERE clause. Something like this:
Dim str_filter As String
Dim str_recSource As String
str_recSource = Me.RecordSource
str_filter = Me.Filter
CurrentDb.Execute "DELETE * FROM MyExportTable"
If str_filter = "" Or Me.FilterOn = False Then
CurrentDb.Execute "INSERT INTO MyExportTable SELECT * FROM (" & Replace(str_recSource, ";", "") & ") as t"
Else
CurrentDb.Execute "INSERT INTO MyExportTable SELECT * FROM (" & Replace(str_recSource, ";", "") & ") as t" & " WHERE " & str_filter
End If
I'm having a problem with a database I created in MS Access 2003.
There is a table (let's call it tblItems) with four fields: id, description, category, sub_category. The sub_category field is the only one which is not required and allows zero-length data.
I created a form based on this table (frmAddItems) which has two combo-boxes (cboCategory & cboSubCategory), a text box (txtDescription) and a sub-form (sbfExistingItems) which is supposed to list existing items based on what was selected in the two combo-boxes. This works perfectly as long as a sub-category is selected, but if there's no sub-category, sbfExistingItems is empty.
The Record Source for sbfExistingItems is: "SELECT tblItems.id, tblItems.description, tblItems.category, tblItems.sub_category FROM tblItems ORDER BY [description];"
frmAddItems and sbfExistingItems are linked as follows:
Child Fields: category;sub_category
Master Fields: cboCategory;cboSubCategory
The problem is presumably related to how Access handles zero-length data, but I don't know how to make it do what I want it to do. Any help would be greatly appreciated.
Update
As suggested by jhTuppeny, I have removed the child/master links on the subform and added the following code:
Private Sub txtDescription_GotFocus()
Dim sql As String
sql = "SELECT id, description, category, sub_category FROM tblItems"
If IsNull(Me!cboCategory) Or Me!cboCategory = "" Then
' leave recordsource unfiltered
ElseIf IsNull(Me!cboSubCategory) Or Me!cboSubCategory= "" Then
sql = sql & " WHERE [category] = '" & Me!cboCategory & "'"
Else
sql = sql & " WHERE [category] = '" & Me!cboCategory & "' AND [sub_category] = '" & Me!cboSubCategory & "'"
End If
sql = sql & " ORDER BY [description];"
Me!sbfExistingItems.Form.RecordSource = sql
End Sub
But now the subform acts like the child/master fields are linked on "id", listing only the current item.
I guess what it comes down to is that I need a way of altering the values of the child/master fields in the subform's form without the main form thinking that I'm trying to leave it while the required txtDescription field is empty.
Your problem is that you have specified a link between the sub category and the subform. When there is no sub category there is no link regardless of the category.
You need to create a query for your subform that will return records based on category and sub category but is not reliant on there being a sub category supplied. You can then set the recordsource of your subform using something like this;
Dim sql As String
sql = "SELECT tblItems.id, tblItems.description, tblItems.category, tblItems.sub_category "
sql = sql & "FROM tblItems "
If cboSubCategory.Value = "" Then
sql = sql & "WHERE (category = cboCategory.Value) "
Else
sql = sql & "WHERE (category = cboCategory.Value) AND (sub_category = cboSubCategory.Value)"
End If
sql = sql & "ORDER BY [description];"
sbfExistingItems.Form.RecordSource = sql
So, we have imported data which we have queried and then created a pivot table off that query. It is essentially a list of files, each having unique ID numbers, and various attributes (file extension, type of document, hash, etc). In any case, this data is based off "hits" on keyword searches from a different program. This means that there might be multiple records for the same Unique ID since there are multiple hits.
The pivot table allows us to illustrate/manipulate via filtering out certain criteria (e.g. we don't want certain file extensions or we don't want records with FIELD X or FIELD Y0. The report is fine, but we want to make a form/query/report/whatever that will pull a "count" (based off unique ID) which ignores duplicates. For example, once all the filters are set in the pivot table, based on the filters/output of the pivot table, we want something like this:
.PDF Files: 200 | total for field x | total field y | etc
.DOCX files: 320 | total for field x | total for field y | etc
Obviously, we want to ignore duplicates of the same Unique ID in the counts.
What is the best way to do this considering we will be manipulating the pivot table dynamically and often? The ideal scenario would to have the pivot table and another object (form/report/etc) open, and as the pivot table is manipulated whatever is displaying counts changes as well.
Here are some very rough notes notes. They are only minimally tested, and using IN would be a disaster with a lot of values, however, it would be easy enough to switch this round and use an excluded list. Perhaps you can get some ideas.
Dim oPTable ''PivotTable
Dim oPM ''PivotMember
Dim oFUpd ''PivotFilterUpdate
Dim oChildren ''ChildMembers
Dim fset ''FieldSet
Dim sWhere As String
Dim sTemp As String
Dim sSQL As String
Dim sDelim As String
Dim aStates As Variant
Dim i As Integer
Dim rs As DAO.Recordset
sDelim = """"
aStates = Array("Cleared", "Checked") ''Possible states
Set oPTable = Forms(0).PivotTable.ActiveView
sWhere = vbNullString
For Each fset In oPTable.FieldSets
sTemp = vbNullString
Set oChildren = oPTable.FieldSets(fset).Member.ChildMembers
For i = 0 To oChildren.Count - 1
Set oPM = oChildren(i)
Set oFUpd = oPM.Field.FieldSet.CreateFilterUpdate
If aStates(oFUpd.StateOf(oPM) - 1) = "Checked" Then
Select Case fset.BoundField.DataType
Case adChar, adLongVarWChar
sTemp = sTemp & "," & sDelim & oPM.Caption & sDelim
Case adInteger
sTemp = sTemp & "," & oPM.Caption
Case adDate
sTemp = sTemp & ",#" & oPM.Caption & "#"
Case Else
'' The above is a very short list.
'' Stop
End Select
End If
Next
If sTemp > vbNullString Then
sWhere = sWhere _
& " AND [" & fset.Name & "] IN ( " & Mid(sTemp, 2) & ")"
End If
Next
sSQL = "SELECT DISTINCT ID FROM [" & oPTable.Control.DataMemberCaption & "] "
sSQL = sSQL & "WHERE 1=1" & sWhere
Set rs = CurrentDb.OpenRecordset(sSQL)
MsgBox "Unique: " & rs.RecordCount
if that helps:
http://lazyvba.blogspot.com/2010/11/improve-your-pivot-table-to-count.html
it will get you the unique count of ID numbers by numbers you want, and you can still manipulate the pivot