迭代 ItemsSelected 并从中生成报告 - 访问 VBA

Iterating ItemsSelected and Generating A Report from it - Access VBA

我有一个由文本框的值填充的列表框。当我单击多个项目并 运行 我的查询时,我得到一个空白结果。字段数据类型均为ShortText。

如果我只选择一项,查询就可以正常工作。这是我的示例代码。

Private Sub txt_testexport_Click()
    Dim db As DAO.Database
    Dim qdf As DAO.QueryDef
    Dim varItem As Variant
    Dim StrSQz As String
    Dim strx As String
    Dim lst As ListBox
            
    Set db = CurrentDb()
    Set qdf = db.QueryDefs("qry_export")
    Set lst = [Forms]![frm_search]![lst_rec]
    
    For Each varItem In Me!lst_rec.ItemsSelected
    strx = strx & "," & Me!lst_rec.ItemData(varItem) & ""
    Next varItem
    
    If Len(strx) = 0 Then
            MsgBox "Nothing Selected from List" _
                , vbExclamation, "Nothing to find"
    Exit Sub
    End If
    
    strx = Right(strx, Len(strx) - 1)
    StrSQz = "SELECT TargetCDRs.OtherParty, TargetCDRs.TargetNumber, TargetCDRs.Description, 
     TargetCDRs.Duration, TargetCDRs.StartDateTimeLocal, " & _
             "TargetCDRs.EndDateTimeLocal, TargetCDRs.Direction, TargetCDRs.SubType " & _
             "FROM TargetCDRs " & _
             "WHERE ((TargetCDRs.OtherParty)=[Forms]![frm_search]![txt_rec]) AND 
    (TargetCDRs.TargetNumber IN('" & strx & "'));"
    
    qdf.SQL = StrSQz
           
    DoCmd.OpenQuery "qry_export"

    
    Set lst = Nothing
    Set db = Nothing
    Set qdf = Nothing
    
 End Sub

表格样本

需要单引号:

strx = strx & ",'" & Me!lst_rec.ItemData(varItem) & "'"

' <snip>

"WHERE (TargetCDRs.OtherParty=[Forms]![frm_search]![txt_rec]) AND 
(TargetCDRs.TargetNumber IN(" & strx & "));"