Access Export Query to Spreadsheet subject to variable conditions? - sql

I have a form with a button, 2 combo boxes as filters, and 3 combo boxes to sort. This button successfully opens a report (trndOTRpt, whose data comes from the query trndOTQry) subject to any criteria that may be chosen and sorted by any sort criteria that may be chosen. I changed the command to instead export the driving query, trndOTQry:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, _
"trndOTQry", _
"\\es3.com\dfsroot$\YK_Share\office_public\D2S\D2S\D2S_Scorecard\OTTest.xls"
This works successfully. But now I want to apply the same VBA code to filter/sort this query as I did with the report. Here is the whole of it:
(The meat & potatoes is at the bottom, notice the commented out code from the original script to open the report. I simply subbed that for the above TransferSpreadsheet action.)
Private Sub SupervisorsGo_Click()
Dim strWhereCondition As String
Dim strSupervisor As String
Dim strPosition As String
Dim varItem As Variant
For Each varItem In Me.SupervisorCombo.ItemsSelected
strSupervisor = strSupervisor & ",'" & Me.SupervisorCombo.ItemData(varItem) _
& "'"
Next varItem
If Len(strSupervisor) = 0 Then
strSupervisor = "Like '*'"
Else
strSupervisor = Right(strSupervisor, Len(strSupervisor) - 1)
strSupervisor = "IN(" & strSupervisor & ")"
End If
For Each varItem In Me.PositionCombo.ItemsSelected
strPosition = strPosition & ",'" & Me.PositionCombo.ItemData(varItem) _
& "'"
Next varItem
If Len(strPosition) = 0 Then
strPosition = "Like '*'"
Else
strPosition = Right(strPosition, Len(strPosition) - 1)
strPosition = "IN(" & strPosition & ")"
End If
strWhereCondition = "[supervisor] " & strSupervisor & _
" AND [position] " & strPosition
If Me.cboSortOrder1.Value <> "Not Sorted" Then
strSortOrder = "[" & Me.cboSortOrder1.Value & "]"
If Me.cmdSortDirection1.Caption = "Descending" Then
strSortOrder = strSortOrder & " DESC"
End If
If Me.cboSortOrder2.Value <> "Not Sorted" Then
strSortOrder = strSortOrder & ",[" & Me.cboSortOrder2.Value & "]"
If Me.cmdSortDirection2.Caption = "Descending" Then
strSortOrder = strSortOrder & " DESC"
End If
If Me.cboSortOrder3.Value <> "Not Sorted" Then
strSortOrder = strSortOrder & ",[" & Me.cboSortOrder3.Value & "]"
If Me.cmdSortDirection3.Caption = "Descending" Then
strSortOrder = strSortOrder & " DESC"
End If
End If
End If
End If
Debug.Print strWhereCondition
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, _
"trndOTQry", _
"\\es3.com\dfsroot$\YK_Share\office_public\D2S\D2S\D2S_Scorecard\OTTest.xls"
' DoCmd.OpenReport "trndOTRpt", View:=acViewPreview, _
' WhereCondition:=strWhereCondition
With Queries![trndOTQry]
.OrderBy = strSortOrder
.OrderByOn = True
End With
End Sub
This fails. While the original code went With Reports![trndOTRpt], I get Run-time Error 424: Object Required with With Queries![trndOTQry] highlighted. I feel like I have adjusted all references appropriately--why is it not acknowledging the object here?
My goal is to export trndOTQry subject to filters/sorts chosen in the form.

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?

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

Access report cannot be closed or refreshed from VB with updated parameter set

A form's button click opens an access report that comes up with data. The parameters are used with a pass-through query to an SQL stored procedure which returns records. The report does not come up Modal and I would like it to remain that way. However, if the user does not close the report before going back to the form and tries to set new parameters, the report remains open in the background and upon the button click the report is brought to the fore with old parameters and data and not refreshed with new parameters/data.
One option is to go Modal with the report but that makes for rough transitions with the user having to actively close the report. The other option is to close the report during retries which is what I have been trying. I have tried:
If CurrentProject.AllReports(rpt_ptq_uspWorkCentreReport).IsLoaded Then
DoCmd.Close acReport, rpt_ptq_uspWorkCentreReport, acSaveNo
in several different locations: _MousedDown, as the first If in the _Click, and _BeforeInsert. Each time CurrentProject.AllReports(rpt_ptq_uspWorkCentreReport).IsLoaded comes up false during the second pass when the report is sitting in the background and the form is being reworked with the next tries new parameters. Also during the second attempt the .OpenReport line fails with an SQL error because strSQLP1 is incomplete. Here's the _Click event:
Private Sub btnPreviewP1_Click()
If (Me.txtToDateP1 < Me.txtFromDateP1) Then
MsgBox ("The From Date must occurr before the To Date!")
End If
Dim strFromDateHMS As String
Dim strToDateHMS As String
Dim strSQLP1 As String
Dim strOpenArgs As String
strFromDateHMS = Format(Me.txtFromDateP1, "yyyy-mm-dd") & " " & Me.cboFromHourP1 & ":" & Me.cboFromMinuteP1 & ":" & Me.cboFromSecondP1
strToDateHMS = Format(Me.txtToDateP1, "yyyy-mm-dd") & " " & Me.cboToHourP1 & ":" & Me.cboToMinuteP1 & ":" & Me.cboToSecondP1
strSQLP1 = "exec dbo.uspWorkCentreReport '" & strFromDateHMS & "','" & strToDateHMS & "','" & strWCP1 & "'," & strShiftP1
strOpenArgs = Me.RecordSource & "|" & strFromDateHMS & "|" & strToDateHMS & "|" & strWCP1 & "|" & strShiftP1
' This line is all that's needed to modify the PT query
CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSQLP1
DoCmd.OpenReport "rpt_ptq_uspWorkCentreReport", acViewReport, , , , strOpenArgs
End Sub
And the _MouseDown where the .AllReports is currently:
Private Sub btnPreviewP1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If CurrentProject.AllReports(rpt_ptq_uspWorkCentreReport).IsLoaded Then
DoCmd.Close acReport, rpt_ptq_uspWorkCentreReport, acSaveNo
End If
End Sub
This is the Report_Open:
Private Sub Report_Open(Cancel As Integer)
Dim SplitOpenArgs() As String
SplitOpenArgs = Split(Me.OpenArgs, "|")
Me.lblFromDate.Caption = SplitOpenArgs(1)
Me.lblToDate.Caption = SplitOpenArgs(2)
Me.lblWC.Caption = SplitOpenArgs(3)
Me.lblShift.Caption = SplitOpenArgs(4)
End Sub
Why not just close report before OpenReport? I modified your code:
Private Sub btnPreviewP1_Click()
If (Me.txtToDateP1 < Me.txtFromDateP1) Then
MsgBox ("The From Date must occurr before the To Date!")
End If
Dim strFromDateHMS As String
Dim strToDateHMS As String
Dim strSQLP1 As String
Dim strOpenArgs As String
Dim R
strFromDateHMS = Format(Me.txtFromDateP1, "yyyy-mm-dd") & " " & Me.cboFromHourP1 & ":" & Me.cboFromMinuteP1 & ":" & Me.cboFromSecondP1
strToDateHMS = Format(Me.txtToDateP1, "yyyy-mm-dd") & " " & Me.cboToHourP1 & ":" & Me.cboToMinuteP1 & ":" & Me.cboToSecondP1
strSQLP1 = "exec dbo.uspWorkCentreReport '" & strFromDateHMS & "','" & strToDateHMS & "','" & strWCP1 & "'," & strShiftP1
strOpenArgs = Me.RecordSource & "|" & strFromDateHMS & "|" & strToDateHMS & "|" & strWCP1 & "|" & strShiftP1
' This line is all that's needed to modify the PT query
CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSQLP1
' Check if report is open and close it without saving:
For Each R In Reports
If R.Name = "rpt_ptq_uspWorkCentreReport" Then
DoCmd.Close acReport, "rpt_ptq_uspWorkCentreReport", acSaveNo
Exit For
End If
Next R
DoCmd.OpenReport "rpt_ptq_uspWorkCentreReport", acViewReport, , , , strOpenArgs
End Sub

Reserved Error when capturing changes on Access 2013 Form

I'm using the code within the following link within an Access 2013 form to capture changes made to records: https://www.techrepublic.com/article/a-simple-solution-for-tracking-changes-to-access-data/
I have the ErrorHandler commented out and am getting a "<Reserved Error>" within the line: If (.Value <> .OldValue or ((Not IsNull .... This causes the statement not to read True and is skipped over.
I'm calling this Sub in BeforeUpdate trigger on the Review Form:
Sub ReviewFormAuditTrail(frm As Form, recordid As Control)
'Track changes to data.
'recordid identifies the pk field's corresponding
'control in frm, in order to id record.
Dim ctl As Control
Dim varBefore As Variant
Dim varAfter As Variant
Dim strControlName As String
Dim strSQL As String
Dim ChangeReason As Variant
'On Error GoTo ErrHandler
'Get changed values.
For Each ctl In frm.Controls
With ctl
'Avoid labels and other controls with Value property.
If .ControlType = acComboBox Then
'Changed this is allow for both null to value and value to null
If (.Value <> .OldValue) Or ((Not IsNull(.OldValue) And IsNull(.Value))) Or ((IsNull(.OldValue) And Not IsNull(.Value))) Then
varBefore = .OldValue
varAfter = .Value
strControlName = .Name
ChangeReason = Forms![Review Form]!ChangeReason
'Build INSERT INTO statement.
strSQL = "INSERT INTO " _
& "xAudit (EditDate, User, RecordID, SourceTable, " _
& " SourceField, BeforeValue, AfterValue, ChangeReason) " _
& "VALUES (Now()," _
& cDQ & Environ("username") & cDQ & ", " _
& cDQ & recordid.Value & cDQ & ", " _
& cDQ & frm.RecordSource & cDQ & ", " _
& cDQ & .Name & cDQ & ", " _
& cDQ & varBefore & cDQ & ", " _
& cDQ & varAfter & cDQ & "," _
& cDQ & ChangeReason & cDQ & ")"
'View evaluated statement in Immediate window.
Debug.Print strSQL
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
End If
ElseIf .ControlType = acTextBox Then
'Changed this is allow for both null to value and value to null
If (.Value <> .OldValue) Or ((Not IsNull(.OldValue) And IsNull(.Value))) Or ((IsNull(.OldValue) And Not IsNull(.Value))) Then
varBefore = .OldValue
varAfter = .Value
strControlName = .Name
ChangeReason = Forms![Review Form]!ChangeReason
'Build INSERT INTO statement.
strSQL = "INSERT INTO " _
& "xAudit (EditDate, User, RecordID, SourceTable, " _
& " SourceField, BeforeValue, AfterValue, ChangeReason) " _
& "VALUES (Now()," _
& cDQ & Environ("username") & cDQ & ", " _
& cDQ & recordid.Value & cDQ & ", " _
& cDQ & frm.RecordSource & cDQ & ", " _
& cDQ & .Name & cDQ & ", " _
& cDQ & varBefore & cDQ & ", " _
& cDQ & varAfter & cDQ & "," _
& cDQ & ChangeReason & cDQ & ")"
'View evaluated statement in Immediate window.
Debug.Print strSQL
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
End If
End If
End With
Next
Set ctl = Nothing
Exit Sub
'Added to ignore the error produced from processing in joined tables
ErrHandler:
'If Err.Number = 3251 Then
' Response = acDataErrContinue
'Else
' MsgBox Err.Description & vbNewLine _
' & Err.Number, vbOKOnly, "Error"
'End If
End Sub
Consider the industry standard when using SQL at application layer (i.e., VBA) by using a parameterized query with MS Access' QueryDef.Parameters which I assume is the crux of your issue.
With this approach you divorce SQL from VBA for better readability and maintainability without need to concatenate or enclose with quotes. Your above link runs a VBA concatenated SQL string and curiously does not combine the two repetitive If blocks:
SQL (save as you would any MS Access query)
PARAMETERS paramEditDate Date, paramUser Text(255), paramRecordID Long,
paramSourceTable Text(255), paramSourceField Text(255),
paramBeforeValue Text(255), paramAfterValue Text(255), paramChangeReason Text(255);
INSERT INTO xAudit (EditDate, [User], RecordID, SourceTable
SourceField, BeforeValue, AfterValue, ChangeReason)
VALUES (paramEditDate, paramUser, paramRecordID, paramSourceTable,
paramSourceField, paramBeforeValue, paramAfterValue, paramChangeReason);
VBA (pass form name as argument and use Forms() collection)
Sub ReviewFormAuditTrail(frm_name As String, recordid As Control)
On Error GoTo ErrHandler
'Track changes to data.
'recordid identifies the pk field's corresponding
'control in frm, in order to id record.
Dim ctl As Control
Dim varBefore As Variant, varAfter As Variant, ChangeReason As Variant
Dim strControlName As String, strSQL As String
Dim qdef As QueryDef
'Get changed values.
For Each ctl In Forms(frm_name).Controls
With ctl
'Avoid labels and other controls with Value property.
If .ControlType = acComboBox Or .ControlType = acTextBox Then
'Changed this is allow for both null to value and value to null
If (.Value <> .OldValue) Or ((Not IsNull(.OldValue) And IsNull(.Value))) _
Or ((IsNull(.OldValue) And Not IsNull(.Value))) Then
varBefore = .OldValue
varAfter = .Value
strControlName = .Name
ChangeReason = Forms![Review Form]!ChangeReason
' RETRIEVE SAVED QUERY
Set qdef = CurrentDb.QueryDefs("mySavedQuery")
' BIND PARAMS
qdef!paramEditDate = Now()
qdef!paramUser = Environ("username")
qdef!paramRecordID = recordid.Value
qdef!paramSourceTable = Forms(frm_name).RecordSource
qdef!paramSourceField = strControlName
qdef!paramBeforeValue = varBefore
qdef!paramAfterValue = varAfter
qdef!paramChangeReason = ChangeReason
' EXECUTE QUERY
qdef.Execute dbFailOnError
End If
End if
End With
Next ctl
ExitHandler:
Set ctl = Nothing: Set qdef = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description & vbNewLine & Err.Number, vbOKOnly, "Runtime Error"
Resume ExitHandler
End Sub

VBA SQL query result error

There's no result or blank excel sheet in result of following SQL query. It works fine if I remove where condition but Its required. So kindly help me to correct my code with where condition. Code is follow-
Private Sub cmdOpenQuery_Click()
Dim strTableName As String
Dim strFieldName As String
Dim strFieldValue As String
Dim strFV As String
Dim strFieldType As String
Dim strBaseSQL As String
Dim strCriteria As String
Dim varItem As Variant
Dim strSQL As String
Dim qdf As DAO.QueryDef
Dim OutPut As String
Dim intCounter As Integer
Dim xlApp As Object
For Each qdf In CurrentDb.QueryDefs
If qdf.Name = "MyQry" Then
DoCmd.DeleteObject acQuery, "MyQry"
Exit For
End If
Next
strTableName = Me.[cboSelectTblQry]
strFieldName = Me.[cboWhere]
strFV = Me.[cboEqualto]
strFieldType = CurrentDb.TableDefs(Me.cboSelectTblQry).Fields(Me.cboWhere).Type
If strFieldType = 4 Then
strFieldValue = "[" & strFV & "]"
ElseIf strFieldType = 10 Then
strFieldValue = "['" & strFV & "']"
ElseIf strFieldType = 8 Then
strFieldValue = "[#" & strFV & "#]"
End If
strBaseSQL = "SELECT "
For intCounter = 0 To lstSelectTo.ListCount
lstSelectTo.Selected(intCounter) = True
Next intCounter
For Each varItem In Me![lstSelectTo].ItemsSelected
strCriteria = strCriteria & "[" & Me![lstSelectTo].ItemData(varItem) & "],"
Next
strSQL = strBaseSQL & Left$(strCriteria, Len(strCriteria) - 1) & " FROM [" & strTableName & "]" & " Where [" & strFieldName & "] = strFieldValue "
Set qdf = CurrentDb.CreateQueryDef("MyQry", strSQL)
If cboFormat = "Excel" Then
OutPut = "D:/Export_" & strTableName & "_" & Date & ".xlsx"
DoCmd.TransferSpreadsheet acExport, , "MyQry", OutPut
MsgBox " File has been exported to " & OutPut
DoCmd.Close
DoCmd.OpenForm "frmCreateQry"
Set xlApp = CreateObject("Excel.Application")
xlApp.Workbooks.Open (OutPut)
xlApp.Visible = True
ElseIf cboFormat = "PDF" Then
OutPut = "D:/Export_" & strTableName & "_" & Date & ".pdf"
DoCmd.OutputTo acOutputQuery, "MyQry", acFormatPDF, OutPut, True
MsgBox " File has been exported to " & OutPut
ElseIf cboFormat = "Word" Then
End If
ExitSub:
Exit Sub
ErrorHandler:
Resume ExitSub
End Sub
Your where condition is using strFieldValue as the value to look for. You should instead use the use held by strFieldValue for comparison. You're doing that properly with strTableName already. It is the same idea here. You'd need to enclose the value of strFieldValue in quotes when you add it.
strSQL = strBaseSQL & Left$(strCriteria, Len(strCriteria) - 1) & " FROM [" & strTableName & "]" & " Where [" & strFieldName & "] = '" & strFieldValue & "'"
I made some corrections and it's working now fine for all format like numeric, text and date type.
Following corrections made in Type condition :-
If strFieldType = 4 Then
strFieldValue = Me.cboEqualto
ElseIf strFieldType = 10 Then
strFieldValue = "'" & strFV & "'"
ElseIf strFieldType = 8 Then
strFieldValue = "#" & strFV & "#"
End If
and following correction in strSQL:-
strSQL = strBaseSQL & Left$(strCriteria, Len(strCriteria) - 1) & " FROM [" & strTableName & "]" & " Where [" & strFieldName & "] = " & strFieldValue & ""