从列表框中删除项目(MS Access VBA)
Posted
技术标签:
【中文标题】从列表框中删除项目(MS Access VBA)【英文标题】:Remove Item from List box (MS Access VBA) 【发布时间】:2019-12-16 19:43:52 【问题描述】:我有一个包含要处理的文件名的列表框;多选选项。文件的处理工作。我希望在处理文件的每次迭代后更新列表框,以便从列表框中删除文件名。下面的代码确实删除了选定的项目,但随后取消选择所有剩余的项目,因此不会执行文件处理的后续迭代。如何从当前迭代的列表框中删除选定的文件,但保留其他文件的选择并继续该过程?
非常感谢。
Function RemoveListItem(ctlListBox As ListBox, ByVal varItem As Variant) As Boolean
Dim i As Integer
On Error GoTo ERROR_HANDLER
i = varItem
If ctlListBox.Selected(i) = True Then
ctlListBox.RemoveItem (i)
End If
On Error GoTo 0
Exit Function
ERROR_HANDLER:
RemoveListItem = False
End Function
这会填满列表框:
Public Function ListFiles(strPath As String, Optional strFileSpec As String, _
Optional bIncludeSubfolders As Boolean, Optional lst As ListBox)
On Error GoTo Err_Handler
'Purpose: List the files in the path.
'Arguments: strPath = the path to search.
' strFileSpec = "*.*" unless you specify differently.
' bIncludeSubfolders: If True, returns results from subdirectories of strPath as well.
' lst: if you pass in a list box, items are added to it. If not, files are listed to immediate window.
' The list box must have its Row Source Type property set to Value List.
'Method: FilDir() adds items to a collection, calling itself recursively for subfolders.
Dim colDirList As New Collection
Dim varItem As Variant
Call FillDir(colDirList, strPath, strFileSpec, bIncludeSubfolders)
'Add the files to a list box if one was passed in. Otherwise list to the Immediate Window.
For Each varItem In colDirList
lst.AddItem varItem
Next
Exit_Handler:
Exit Function
Err_Handler:
MsgBox "Error " & Err.Number & ": " & Err.Description
Resume Exit_Handler
End Function
将 RemoveListItem 更新为评论中的代码:ERIK A....
由于此删除项目代码向后工作,因此我必须将文件处理也更改为向后工作,即最后选择的文件是要处理的第一个文件。我使用以下内容来完成我的文件导入过程。它从选择的第一个文件开始。我该如何反向执行此操作?使用与删除项中相同的逻辑/代码?
For Each varItem In ctl.ItemsSelected
strFileName = ctl.ItemData(varItem)
....File Import Process....
Next
【问题讨论】:
首先了解列表框的填充方式会有所帮助。请使用问题下方的edit 链接来包含该代码。 由于您要从集合中删除项目,因此您可能正在迭代,因此该函数的调用代码似乎也很相关。 我想你们都要求同样的事情......填充列表框的代码已添加到帖子中。谢谢。 【参考方案1】:更改行源会清除所选项目。这意味着您必须存储Selected
,然后以相反的顺序删除以防止位置移动:
Public Sub RemoveListItem(lstSource As ListBox)
Dim intListX As Integer
Dim selectedItems As Collection
Set selectedItems = New Collection
For intListX = lstSource.ListCount - 1 to 0 step -1
If lstSource.Selected(intListX) Then
selectedItems.Add intListX 'Add the items to be removed to a collection, in reverse order
End If
intListX = intListX - 1
Loop
Dim iterator As Variant
For Each iterator In selectedItems
lstSource.RemoveItem iterator 'And then remove them
Next iterator
End Sub
本文略有改编自this answer
【讨论】:
以上是关于从列表框中删除项目(MS Access VBA)的主要内容,如果未能解决你的问题,请参考以下文章
单击列表框时,如何在文本框中以另一种形式从ms access 2010中的列表框中移动所选项目