我们说我有一个名为" Customers"的表。它包含2个字段:
Name
Address
我希望用户能够通过选择他们的名字来选择多个记录。例如,有一个列表框包含数据库中记录的所有名称。我希望用户能够选择多个项目,如:
Dave Richardson
Bob Smith
Sophie Parker
然后只在报告中显示带有这些名称的记录。
答案 0 :(得分:3)
您可以使用DoCmd.OpenReport Method的 WhereCondition 选项根据需要过滤报告。
Const cstrReport As String = "YourReportNameHere"
Dim custNames As String
Dim lItem As Variant
Dim strWhereCondition As String
With Me.yourListBoxName
For Each lItem In .ItemsSelected
custNames = custNames & ",'" & Replace(.ItemData(lItem), "'", "''") & "'"
Next
End With
If Len(custNames) > 0 Then
custNames = Mid(custNames, 2)
strWhereCondition = "[Name] IN (" & custNames & ")"
End If
DoCmd.OpenReport ReportName:=cstrReport, View:=acViewPreview, _
WhereCondition:=strWhereCondition
请注意,这种方法与PaulFrancis有相同的特点。回答。事实上,我复制了他的代码并对其进行了修改。关键区别在于此方法不需要您修改已保存的查询以过滤报告。
答案 1 :(得分:2)
我将拥有的设置是带有SubForm和ListBox的表单,列表框将包含所有客户的名称。所以RowSource就是,
SELECT
customerNameFieldName
FROM
yourTableName;
Multi Select
属性将设置为Extended
。然后一个按钮将具有以下代码,该代码将为SubForm的记录源生成SQL。
Private Sub buttonName_Click()
Dim lItem As Varaint, strSQL As String
Dim custNames As String, whereStr As String
Dim dbObj As dao.Database
Dim tmpQryDef As QueryDef
Set dbObj = CurrentDb()
For Each lItem In Me.yourListBoxName.ItemsSelected
custNames = custNames & "'" & Me.yourListBoxName.ItemData(lItem) & "', "
Next
Id Len(custNames) <> 0 Then
custNames = Left(custNames, Len(custNames) - 2)
whereStr = "WHERE customerNameFieldName IN (" & custNames & ")"
End If
strSQL = "SELECT someFields FROM someTable " & whereStr
Set tmpQryDef = dbObj.QueryDefs("Summary 3 Q1")
tmpQryDef.SQL = strSQL
DoCmd.OpenReport "yourReportName", acViewNormal
Set dbObj = Nothing
Set tmpQryDef = Nothing
End Sub
所以现在SubForm将根据你在ListBox中选择的所有信息来创建RecordSource。