Here's what I have so far. I have frmCreateInvoice which contains an unbound listbox and a button to run a query. These are named lstCustomers and cmdOpenQuery, respectively. lstCustomers row source is as follows:
SELECT DISTINCT tblCustomers.InstitutionName FROM tblCustomers UNION SELECT "All" FROM tblCustomers;
cmdOpenQuery has some VBA on click event, which is supposed to allow users to select one or many Institution Names from the listbox and run qryCreateInvoice when clicked. The part in red is the trouble. The code works when I use strSQL = "SELECT * FROM tblCustomers, but when I try to select certain fields to use, I run into problems. Here is the code:
Option Compare Database
Private Sub cmdOpenQuery_Click()
On Error GoTo Err_cmdOpenQuery_Click
Dim MyDB As DAO.Database
Dim qdef As DAO.QueryDef
Dim i As Integer
Dim strSQL As String
Dim strWhere As String
Dim strIN As String
Dim flgSelectAll As Boolean
Dim varItem As Variant
Set MyDB = CurrentDb()
strSQL = "SELECT tblCustomers.CustomerID, tblCustomers.BillingID, [Enter Report Date] AS ReportDate, Date() AS BillingDate, tblFeeTypes.FeeName, tblCustomerFees.FeeAmount, tblCustomers.ContactName, tblCustomers.Address, tblCustomers.BrokerPay, [tblCustomers]![City]+", "+[tblCustomers]![State]+" "+[tblCustomers]![Zip] AS CityStateZip, tblCustomers.Cancelled
FROM (tblCustomers INNER JOIN tblCustomerFees ON tblCustomers.CustomerID = tblCustomerFees.CustomerID) INNER JOIN tblFeeTypes ON tblCustomerFees.FeeTypeID = tblFeeTypes.FeeTypeID
WHERE (((tblCustomers.Cancelled)=False))"
'Build the IN string by looping through the listbox
For i = 0 To lstCustomers.ListCount - 1
If lstCustomers.Selected(i) Then
If lstCustomers.Column(0, i) = "All" Then
flgSelectAll = True
End If
strIN = strIN & "'" & lstCustomers.Column(0, i) & "',"
End If
Next i
'Create the WHERE string, and strip off the last comma of the IN string
strWhere = " WHERE [InstitutionName] in (" & Left(strIN, Len(strIN) - 1) & ")"
'If "All" was selected in the listbox, don't add the WHERE condition
If Not flgSelectAll Then
strSQL = strSQL & strWhere
End If
MyDB.QueryDefs.Delete "qryCreateInvoice"
Set qdef = MyDB.CreateQueryDef("qryCreateInvoice", strSQL)
'Open the query, built using the IN clause to set the criteria
DoCmd.OpenQuery "qryCreateInvoice", acViewNormal
'Clear listbox selection after running query
For Each varItem In Me.lstCustomers.ItemsSelected
Me.lstCustomers.Selected(varItem) = False
Next varItem
Exit_cmdOpenQuery_Click:
Exit Sub
Err_cmdOpenQuery_Click:
If Err.Number = 5 Then
MsgBox "You must make a selection(s) from the list" _
, , "Selection Required !"
Resume Exit_cmdOpenQuery_Click
Else
'Write out the error and exit the sub
MsgBox Err.Description
Resume Exit_cmdOpenQuery_Click
End If
End Sub