Unable to Filter - vba

I am trying to write an SQL code in my MS Access database whereby the filter on Entity_name is not working properly
Function FilterResults()
Dim strCriteria As String
strCriteria = ""
If Nz(Me.cboEntitynameFilter) <> "" Then
strEntityNameFilter = "Entity_Name = '" & Me.cboEntitynameFilter & "'"
Else
strEntityNameFilter = "Entity_Name = '*'"
End If
If Nz(Me.cboAssignmentFilter) <> "" Then
strAssignmentFilter = " AND " & "Assignment = '" & Me.cboAssignmentFilter & "'" '& " AND "
End If
If Nz(Me.cboFYFilter) <> "" Then
strFYFilter = " AND " & "Financial_Year = '" & Me.cboFYFilter & "'"
End If
strCriteria = Nz(strEntityNameFilter, "*") & Nz(strAssignmentFilter, "*") & Nz(strFYFilter, "*")
' End If
If strCriteria = ("Entity_Name = '*'") Then
Me.Filter = ""
Me.FilterOn = False
Else
If strCriteria <> "" Then
Me.Filter = strCriteria
Me.FilterOn = True
End If
End If
End Function
The strCriteria returned is
Entity_Name = '*' AND Assignment = 'MFI'
The filter doesn't work and the Entity_Name is all blank. What am I doing wrong.
I am using this in MS-Access and building query in VBA

I would do like this
Dim strCriteria AS string
strCriteria = "1 = 1"
If Len(Nz(Me.cboEntitynameFilter, "")) > 0 Then
strCriteria = strCriteria & " and [Entity_Name] = """ & Me.cboEntitynameFilter & """"
End If
If Len(Nz(Me.cboAssignmentFilter, "")) > 0 Then
strCriteria = strCriteria & " and [Assignment] = """ & Me.cboAssignmentFilter & """"
End If
If Len(Nz(Me.cboFYFilter, "")) > 0 Then
strCriteria = strCriteria & " and [Financial_Year] = """ & Me.cboFYFilter & """"
End If
Me.Filter = strCriteria
Me.FilterOn = True
if any of the combobox or textbox didn't select than it will igonre those field.

Related

Filter problem when ms access report is created

I have a form with information about how long the citizens have lived in which state and city.I have txt boxes to give time range. I have comboboxes where I can select cities according to the selected state or states (Multiple Selection Options). And I have a report generation button that uses these filters.
Function searchCriteria() As String 'Filtering with City and State
Dim strFilter, strCriteria, strSQL As String
Select Case cmb_State  Case Is = ""    
 If Me.cmb_City = "<Multi Selection>" Then         
strCriteria = "[City] in (" & TempVars!TempMultiCity & ")"
 Else        
strCriteria = "[City] ='" & Me.cmb_City & "'"
End If   
   
Case Is = "<Multi Selection>"
  If IsLbUsed(Me.lbKSALL) = True Then
  If IsNull(Me.cmb_City) Or Me.cmb_City = "" Then
            strCriteria = "[State] in (" & TempVars!TempMultiState & ")" 
     ElseIf Me.cmb_City = "<Multi Selection>" Then 
     If IsLbUsed(Me.lbKTALL) = True Then
        strCriteria = "[City] in (" & TempVars!TempMultiCity & ")"             
Else  
strCriteria = "[State] in (" & TempVars!TempMultiState & ")"
     End If 
  Else 
      strCriteria = "[City] ='" & Me.cmb_City & "'"
  End If
  Else  
      strCriteria = "[City] ='" & Me.cmb_City & "'" 
  End If
Case Else
If IsNull(Me.cmb_City) Or Me.cmb_City = "" Then 
      strCriteria = "[State]='" & Me.cmb_State & "'"      
ElseIf Me.cmb_City = "<Multi Selection>" Then 
        strCriteria = "[City] in (" & TempVars!TempMultiCity & ")"
Else  strCriteria = "[State]='" & Me.cmb_State & "'" 
        strCriteria = strCriteria & " AND [City] ='" & Me.cmb_City & "'"
   End If      
End Select
searchCriteria = strCriteria
End Function
===========================================================================================
Sub search() ' Applies function searchcriteria and gets the datas from query
Dim strCriteria As String
strCriteria = searchCriteria()
strSQL = "select * from qryForForm where(" & strCriteria & ")"
Me.RecordSource = strSQL
Me.Requery
End Sub
======================================================================================
Private Sub cmd_ReportAll_Click() ' applies all filter that I used in my Form
Dim strCriteria As String
If IsNull(Me.txtFrom) Or IsNull(Me.txtTo) Then ' txt boxes for time range filter
strCriteria = searchCriteria()
DoCmd.OpenReport "All", acViewPreview, , strCriteria
Else
strCriteria = searchCriteria()
DoCmd.OpenReport "All", acViewPreview, , strCriteria & " And [LivingDate] Between #" & Format(Me.txtFrom, "yyyy\/mm\/dd") & "# And #" & Format(Me.txtTo, "yyyy\/mm\/dd") & "#"
End If
Call search
End Sub
The problem is: if I want to generate a report without selecting state and city (both are not being selected), it doesn't show any data. How can I solve this?

How do I exlude records from my database if a checkbox is false?

I have this split form with some basic search functions based on comboboxes and search fields. Now I want to exclude the records where my checkbox chk_NonC = false.
The VBA-code I currently use to filter my record source qry_Administration:
Function SearchCriteria()
Dim Customer, CustomerLocation, CustomerLocationPlace, ExecutionDate, Material As String
Dim Intern, Extern As String
Dim task, strCriteria As String
If Me.chk_AuditEX = True Then
Extern = "[AuditEX] = " & Me.chk_AuditEX
Else
Extern = "[AuditEX] like '*'"
End If
If Me.chk_AuditIN = True Then
Intern = "[AuditIN] = " & Me.chk_AuditIN
Else
Intern = "[AuditIN] like '*'"
End If
If IsNull(Me.cbo_CustomerLocations) Then
CustomerLocation = "[CustomerLocationID] like '*'"
CustomerLocationPlace = "[LocationCompanyPlace] like '*'"
Else
CustomerLocation = "[LocationCompanyName] = '" & Me.cbo_CustomerLocations.Column(0) & "'"
CustomerLocationPlace = "[LocationCompanyPlace] = '" & Me.cbo_CustomerLocations.Column(1) & "'"
End If
If IsNull(Me.cbo_Customers) Then
Customer = "[CustomerID] like '*'"
Else
Customer = "[CustomerID] = " & Me.cbo_Customers
End If
If IsNull(Me.txt_ExecutionDateTo) Then
ExecutionDate = "[ExecutionDate] like '*'"
Else
If IsNull(Me.txt_ExecutionDateFrom) Then
ExecutionDate = "[ExecutionDate] like '" & Me.txt_ExecutionDateTo & "'"
Else
ExecutionDate = "([ExecutionDate] >= #" & Format(Me.txt_ExecutionDateFrom, "mm/dd/yyyy") & "# And [ExecutionDate] <= #" & Format(Me.txt_ExecutionDateTo, "mm/dd/yyyy") & "#)"
End If
End If
If IsNull(Me.cbo_Material) Or Me.cbo_Material = "" Then
Material = "[MaterialID] like '*'"
ElseIf Me.cbo_Material = 6 Then
Material = "[MaterialID] in (" & TempVars!tempMaterial & ")"
Else
Material = "([MaterialID] = " & Me.cbo_Material & ")"
End If
strCriteria = Customer & "And" & CustomerLocation & "And" & CustomerLocationPlace & "And" & _
& ExecutionDate & Material & "And" & Extern & "And" & Intern
task = "Select * from qry_Administration where (" & strCriteria & ") order by ExecutionDate DESC"
Debug.Print (task)
Me.Form.RecordSource = task
Me.Form.Requery
End Function
Now I want to add this new checkbox Non-Compliant named chk_NonC
When I set chk_NonC to true and press search I want my split-form to show all records.
When I set chk_NonC to false and press search I want my split-form to hide all records where Non_compliant is true
You can see it as a hide function for my database. If I set this checkbox to false then hide all records where non-compliant is set to true.
Please note that function SearchCriteria is called on the OnChange Events of the comboboxes or by clicking a search-icon on the top of my split-form.
Just follow the same flow defined for the other controls.
Create the string portion for the compliance and append it to the rest of the sql script.
Dim strCompliant As String
strCompliant = IIf(Me.chk_NonC,"[Non_compliant]=True","[Non_compliant]=False")
strCriteria = Customer & " And " [...] & " And " & strCompliant
Keep in mind, you need spaces between the " And " joins in strCriteria.

Have a List box that Filters on items within my subform that is a query

I have a list box that has three different categories to choose from on the form. I have vba code that is working that allows me to select more than one item in the list box which is fine. But the items I am selecting I am having troubles to get the results that I need.
For an Example; The three categories within the list box are not in the query with the actual category names. One Category I have is called "Picking" okay, I want to select "picking" and then when the button is clicked I want it to pull all Items within the query field "Item Number" that equals '0801' which represents the Category "Picking".
Note the code behind the button is a simple "On Click" Event Procedure
**The List box I am Having troubles with is called (StrAccounts)
**Picking which is the same thing as Acct in the query that I am trying filter on in in tbUpload
**I want the "Picking" Category in the List box to filter on Acct in the query where Acct = '0801'
**Placed_Orders which the Second category name within my ListBox and it is the same field in the query above "tbUpload", Acct, except I want
this Placed_Orders to get all Acct in ('1108', '1114', '1117', '1113',
'1110')
**Whatever Acct in the query tbUpload that doesn't contain the following numbers already mention above is the third category in my
list box which is "Not_Placed"
**So whenever Not_Placed in the list box is clicked and the search button is selected I want Accts in the query to pull, Accts <>
'0801','1108','1114','1117','1113','1110'
Private Sub cmdSearch_Click()
Dim Varitem As Variant
Dim StrDEPT_OBS As String
Dim StrStatus As String
Dim StrACCT As String
Dim strSQL As String
Dim StrAccounts As String
'get selections from DEPT_OBS multiselect listbox
For Each Varitem In Me!List_Dept_OBS.ItemsSelected
StrDEPT_OBS = StrDEPT_OBS & ",'" & Me!List_Dept_OBS.ItemData(Varitem) & "'"
Next
'get selections from Status multiselect listbox
For Each Varitem In Me!List_Status.ItemsSelected
StrStatus = StrStatus & ",'" & Me!List_Status.ItemData(Varitem) & "'"
Next
'get selections from Accts multiselect listbox
For Each Varitem In Me!List_ACCTs.ItemsSelected
StrStatus = StrAccounts & ",'" & Me!List_ACCTs.ItemData(Varitem) & "'"
Next
If Len(StrDEPT_OBS) > 0 Then
StrDEPT_OBS = Right(StrDEPT_OBS, Len(StrDEPT_OBS) - 1)
Else: MsgBox "You must enter an OBS"
Exit Sub
End If
If Len(StrStatus) > 0 Then
StrStatus = Right(StrStatus, Len(StrStatus) - 1)
End If
If Len(StrAccounts) > 0 Then
StrAccounts = Right(StrAccounts, Len(StrAccounts) - 1)
End If
strSQL = " SELECT * FROM tbUpload WHERE "
strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") AND "
If Len(StrStatus) = 0 Then
strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") "
Else
strSQL = strSQL & "tbUpload.OPR_STAT_ID IN (" & StrStatus & ") "
End If
If Len(StrAccounts) = 0 And StrAccounts = "Picking" Then
strSQL = strSQL & "tbUpload.ACCT like (" & [0801] & ")"
Else
End If
If Len(StrAccounts) = 0 And StrAccounts = "Placed_Orders" Then
strSQL = strSQL & "tbUpload.ACCT IN (" & [1108] & [1114] & [1117] & [1113] & [1110] & ") "
Else
strSQL = strSQL & "tbUpload.ACCT <> (" & [0801] & [1108] & [1114] & [1117] & [1113] & [1110] & ") " "Not_Placed"
End If
DoCmd.SetWarnings False
''DoCmd.OpenQuery ("UPLOAD")
Me![tbUpload subform].Form.RecordSource = strSQL
End Sub
If Len(StrAccounts) > 0 Then
'' StrAccounts = Right(StrAccounts, Len(StrAccounts) - 1)
StrAccounts = StrAccounts & ",'" & Me!List_ACCTs.ItemData(Varitem) & "'"
End If
strSQL = " SELECT * FROM tbUpload WHERE "
strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") AND "
If Len(StrStatus) = 0 Then
strSQL = strSQL & "tbUpload.DEPT_ID IN (" & StrDEPT_OBS & ") "
Else
strSQL = strSQL & "tbUpload.OPR_STAT_ID IN (" & StrStat us & ") "
End If
If StrAccounts = "Lugging" Then
strSQL = strSQL & "tbUpload.ACCT like (" & [0801] & ")"
Else
End If
If StrAccounts = "Structure" Then
strSQL = strSQL & "tbUpload.ACCT IN (" & [1108] & [1114] & [1117] & [1113] & [1110] & ") "
Else
End If
Consider:
'get selections from DEPT_OBS multiselect listbox
For Each Varitem In Me.List_Dept_OBS.ItemsSelected
StrDEPT_OBS = StrDEPT_OBS & ",'" & Me.List_Dept_OBS.ItemData(Varitem) & "'"
Next
If Len(StrDEPT_OBS) > 0 Then
StrDEPT_OBS = "[Dept_ID] IN(" & Right(StrDEPT_OBS, Len(StrDEPT_OBS) - 1) & ") AND "
Else
MsgBox "You must enter an OBS"
Exit Sub
End If
'get selections from Status multiselect listbox
For Each Varitem In Me.List_Status.ItemsSelected
StrStatus = StrStatus & ",'" & Me.List_Status.ItemData(Varitem) & "'"
Next
If Len(StrStatus) > 0 Then
StrStatus = "[OPR_STAT_ID] IN(" & Right(StrStatus, Len(StrStatus) - 1) & ") AND "
End If
'get selection from Accts single select listbox and build account parameters array
Select Case Me.List_Accts
Case "Picking"
StrAccounts = "ACCT = 0801 AND "
Case "Placed_Orders"
StrAccounts = "ACCT IN(1108,1114,1117,1113,1110) AND "
Case "Not_Placed"
StrAccounts = "NOT ACCT IN(0801,1108,1114,1117,1113,1110) AND "
End Select
strSQL = StrDEPT_OBS & StrStatus & StrAccounts
If strSQL <> "" Then
strSQL = " WHERE " & Left(strSQL, Len(strSQL) - 5)
End If
Me.[tbUpload subform].Form.RecordSource = "SELECT * FROM tbUpload" & strSQL & ";"
For more info on dynamically building search criteria with VBA, review http://allenbrowne.com/ser-62.html

MS Access vba export form results to excel with where condition

I have a table that has a lot of fields and then a form that takes only a few of those fields. I have a search button on the form where you can select certain records. Is there a way in VBA to export the results from the form but include all the fields from the table.
Here is my attempt from some code that I found:
Private Sub Command49_Click()
Dim strWhere As String
Dim strFile As String
Const strcStub = "SELECT * FROM tblMaster " & vbCrLf
Const strcTail = "ORDER BY ID;"
Const strcExportQuery = "Query1" 'Name of the query for exports.
'Keyword
If Nz(Me.tKW, "") <> "" Then
strWhere = strWhere & "[iavmtitle] Like '*" & Replace(Me.tKW, " '", "''") & "*' AND "
End If
'Release Date From
If Nz(Me.tRF, "") <> "" Then
strWhere = strWhere & "[releaseDate] between " & "#" & Me.tRF & "# AND #" & Me.tRT & "#" & " AND "
End If
'Expliots
If Nz(Me.cmbExploits, "") <> "" Then
strWhere = strWhere & "[knownExploits] = '" & Me.cmbExploits & "' AND "
End If
'Incidents
If Nz(Me.cmdIncidents, "") <> "" Then
strWhere = strWhere & "[knownDodIncidents] = '" & Me.cmdIncidents & "' AND "
End If
'Release Date From
If Nz(Me.txtSaveSend, "") <> "" Then
strWhere = strWhere & "[lastSaved] > " & "#" & Me.txtSaveSend & "#" & " AND "
End If
If strWhere <> "" Then
strWhere = Left(strWhere, Len(strWhere) - 5) 'Remove the extra AND
Me.Filter = strWhere
Me.FilterOn = True
Else
Me.Filter = ""
Me.FilterOn = False
End If
If Me.FilterOn Then
strWhere = "WHERE " & Me.Filter & vbCrLf
End If
CurrentDb.QueryDefs(strcExportQuery).SQL = strcStub & strWhere & strcTail
strFile = "C:\Data\MyExport.xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
strcExportQuery, strFile
End Sub

How to retrieve data between from date to system date using excel VBA (Automation Error)

I am trying to extract a data from an Excel through different Excel using ADODB.Connection but when I am trying to retrieve data between from date to system date I am getting an automation error in Excel.
I have checked various articles but I'm unable to validate those condition because I don't have SQL Server so I am directly putting into Excel coding but again same error I am getting.
Please help......
Sub get_data()
Dim strSQL As String
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim DBPath As String
Dim sconnect As String
DBPath = "\\abc\Quality Report.xlsx"
sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
cnn.Open sconnect
strSQL = "SELECT * FROM [Error_Log$] WHERE "
If cboprocess.Text <> "" Then
strSQL = strSQL & " [Process]='" & cboprocess.Text & "'"
End If
If cboaudittype.Text <> "" Then
If cboprocess.Text <> "" Then
strSQL = strSQL & " AND [Audit_Type]='" & cboaudittype.Text & "'"
Else
strSQL = strSQL & " [Audit_Type]='" & cboaudittype.Text & "'"
End If
End If
If cbouser1.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Then
strSQL = strSQL & " AND [User_Name]='" & cbouser1.Text & "'"
Else
strSQL = strSQL & " [User_Name]='" & cbouser1.Text & "'"
End If
End If
If cborptmgr.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Or cbouser1.Text <> "" Then
strSQL = strSQL & " AND [Reporting_Manager]='" & cborptmgr.Text & "'"
Else
strSQL = strSQL & " [Reporting_Manager]='" & cborptmgr.Text & "'"
End If
End If
If cbotranstyp.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Or cbouser1.Text <> "" Or cborptmgr.Text <> "" Then
strSQL = strSQL & " AND [Transaction_Type]='" & cbotranstyp.Text & "'"
Else
strSQL = strSQL & " [Transaction_Type]='" & cbotranstyp.Text & "'"
End If
End If
If cboperiod.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Or cbouser1.Text <> "" Or cborptmgr.Text <> "" _
Or cbotranstyp.Text <> "" Then
strSQL = strSQL & " AND [Period]='" & cboperiod.Text & "'"
Else
strSQL = strSQL & " [Period]='" & cboperiod.Text & "'"
End If
End If
If cbolocation.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Or cbouser1.Text <> "" Or cborptmgr.Text <> "" _
Or cbotranstyp.Text <> "" Or cboperiod.Text <> "" Then
strSQL = strSQL & " AND [Location]='" & cbolocation.Text & "'"
Else
strSQL = strSQL & " [Location]='" & cbolocation.Text & "'"
End If
End If
If cbofatnfat.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Or cbouser1.Text <> "" Or cborptmgr.Text <> "" _
Or cbotranstyp.Text <> "" Or cboperiod.Text <> "" Or cbolocation.Text <> "" Then
strSQL = strSQL & " AND [Fatal_NonFatal]='" & cbofatnfat.Text & "'"
Else
strSQL = strSQL & " [Fatal_NonFatal]='" & cbofatnfat.Text & "'"
End If
End If
If cbostatus.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Or cbouser1.Text <> "" Or cborptmgr.Text <> "" _
Or cbotranstyp.Text <> "" Or cboperiod.Text <> "" Or cbolocation.Text <> "" Or cbofatnfat.Text <> "" Then
strSQL = strSQL & " AND [Remarks]='" & cbostatus.Text & "'"
Else
strSQL = strSQL & " [Remarks]='" & cbostatus.Text & "'"
End If
End If
If txtfromauditdt.Text <> "" Then
If cboprocess.Text <> "" Or cboaudittype.Text <> "" Or cbouser1.Text <> "" Or cborptmgr.Text <> "" _
Or cbotranstyp.Text <> "" Or cboperiod.Text <> "" Or cbolocation.Text <> "" Or cbofatnfat.Text <> "" _
Or cbostatus.Text <> "" Then
strSQL = strSQL & " AND [Audit_Date] BETWEEN '" & txtfromauditdt.Text & "' AND GETDATE()"
Else
strSQL = strSQL & " [Audit_Date] BETWEEN '" & txtfromauditdt.Text & "' AND GETDATE()"
End If
End If
Debug.Print strSQL
Set rs.ActiveConnection = cnn
rs.Open strSQL, cnn
Sheet1.Range("A42").CopyFromRecordset rs
rs.Close
cnn.Close
End Sub
Below is debug print from strsql
SELECT *
FROM [Error_Log$]
WHERE [Audit_Date] BETWEEN '16-Nov-2015' AND getdate()
Error screenshot
I think your problem is GetDate()
Your approach to building the WHERE clause can also be much simpler:
Sub get_data()
Dim strSQL As String, strWhere As String
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim DBPath As String
Dim sconnect As String
DBPath = "\\abc\Quality Report.xlsx"
sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
cnn.Open sconnect
strSQL = "SELECT * FROM [Error_Log$] WHERE "
strWhere = ""
BuildWhere strWhere, cboprocess.Text, "Process"
BuildWhere strWhere, cboaudittype.Text, "Audit_Type"
BuildWhere strWhere, cbouser1.Text, "User_Name"
BuildWhere strWhere, cborptmgr.Text, "Reporting_Manager"
BuildWhere strWhere, cbotranstyp.Text, "Transaction_Type"
BuildWhere strWhere, cboperiod.Text, "Period"
BuildWhere strWhere, cbolocation.Text, "Location"
BuildWhere strWhere, cbofatnfat.Text, "Fatal_NonFatal"
BuildWhere strWhere, cbostatus.Text, "Remarks"
If txtfromauditdt.Text <> "" Then
strWhere = strWhere & IIf(strWhere <> "", " AND ", "") & "[Audit_Date] BETWEEN '" & _
txtfromauditdt.Text & "' AND #" & Format(Date, "mm/dd/yyyy") & "# "
End If
strSQL = strSQL & strWhere
Debug.Print strSQL
Set rs.ActiveConnection = cnn
rs.Open strSQL, cnn
Sheet1.Range("A42").CopyFromRecordset rs
rs.Close
cnn.Close
End Sub
Sub BuildWhere(ByRef strWhere As String, v As String, fld As String)
If v <> "" Then
strWhere = strWhere & IIf(strWhere <> "", " AND ", "") & _
"[" & fld & "] = '" & v & "'"
End If
End Sub
Finally found out the error cause...
Actually the error was because of the quotes '13-nov-15' which I was using in coding but the same was replacing after with #13-nov-15#. It worked.
As per the #Williams answer's there was a only one correction made for another date but for parameter date the quotes was coming but now its working cool. Thanks to Tim Williams..helps a lot....
You surrounded the first text date with single quotes ', this will make it a string. You need to use the number sign # instead, like this:
Or cbostatus.Text <> "" Then
strSQL = strSQL & " AND [Audit_Date] BETWEEN #" & txtfromauditdt.Text & "# AND GETDATE()"
Else
strSQL = strSQL & " [Audit_Date] BETWEEN #" & txtfromauditdt.Text & "# AND GETDATE()"
End If