我想在多选列表框的列中使用匹配值打开记录集。目前我的代码只会打开并编辑选择的最后一条记录,我希望它能打开所有这些记录。这是我的代码: -
Set oRSAppt = Application.CurrentDb().OpenRecordset("Select * FROM [Appointments] WHERE [SlotID] =" & ListBox.Column(7, ListBox.ItemsSelected))
With oRSAppt
If .BOF = True And .EOF = True Then
MsgBox "No records found", , "Failed"
Exit Sub
Else
.MoveFirst
Do While Not .EOF
.Edit
.Fields("Status").Value = "Invoiced"
.Fields("InvoiceID").Value = vInvoiceID
.Update
.MoveNext
Loop
.Close
End If
End With
此链接建议使用for循环从列表框中获取所选值 http://msdn.microsoft.com/en-us/library/office/ff823015%28v=office.15%29.aspx 但是我不知道如何在sql语句中做到这一点,或者我是否应该这样做 - 也许我只是在看这个问题已经很久了我错过了一个明显的解决方案。任何帮助将不胜感激。
答案 0 :(得分:2)
您需要首先构建SQL语句,是的,您需要使用循环。这样的事情可以解决问题:
Dim strSQL as String
Dim vItm as Variant
Dim oRSAppt As DAO.Recordset
For Each vItm In Me!Listbox.ItemsSelected
strSQL = strSQL & ListBox.Column(7, vItm) & ","
Next vItm
strSQL = left(strSQL,len(strSQL) - 1) ' remove last comma
Set oRSAppt = CurrentDb.OpenRecordset("Select * FROM [Appointments] " _
WHERE [SlotID] In (" & strSQL & ")")