从列表框中删除项目(MS Access VBA)

问题描述 投票:0回答:2

我有一个列表框,其中包含要处理的文件名;多选选项。文件处理有效。我希望在处理完文件的每次迭代后更新列表框,以便从列表框中删除文件名。下面的代码确实删除了选中的项目,但是随后取消选择了所有剩余的项目,因此不会执行文件处理的后续迭代。如何从当前迭代的列表框中删除选定的文件,但保留其他文件的选择并继续该过程?

非常感谢。

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
vba ms-access listbox
2个回答
0
投票

您必须在列表框中向后循环,因为否则,在删除项目时,以下项目将后退一个位置,而以下项目的循环索引是错误的]

For i = ctlListBox.ListCount - 1 to 0 step -1
    If ctlListBox.Selected(i) Then
        ctlListBox.RemoveItem(i)
    End If
Next

0
投票

更改行源将清除所选项目。这意味着您必须存储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改编而成

© www.soinside.com 2019 - 2024. All rights reserved.