VBA - 检查集合中是否存在项目,是否存在明确选择列表框中的其他项目但不存在该项目

时间:2017-10-26 12:31:37

标签: vba excel-vba excel

我正在尝试检查集合中是否存在一个名为“All”的特定项目。

  Private Sub RefreshData_ListBox_Change()

    Dim ListBoxSelected As Collection
    Set ListBoxSelected = New Collection
    LbKey = 0

    Dim ReqValue As String
    Dim ItemReq As String

    For lItem = 0 To SelectRequiredQR.RefreshData_ListBox.ListCount - 1

        If SelectRequiredQR.RefreshData_ListBox.Selected(lItem) = True Then

            LbKey = LbKey + 1

            ReqValue = SelectRequiredQR.RefreshData_ListBox.List(lItem)

            ListBoxSelected.Add ReqValue, CStr(LbKey)

        End If

    Next

    TotalItems = ListBoxSelected.Count

    If TotalItems > 1 Then
  

如果总项目超过1 - 那么我想检查一个项目   在列表框中称为“全部”,如果存在,那么我想清除   在列表框中选择其他项目但不是“全部”

        For i = 1 To TotalItems

            ItemReq = ListBoxSelected(i)


            If ItemReq = "ALL" Then


                For j = TotalItems To 0 Step -1

                    ItemReq = ListBoxSelected(j)


                    If ItemReq <> "ALL" Then

                        'Remove Item from collection 
                        ListBoxSelected.Remove (j)

                        'Remove selection from listbox
                        SelectRequiredQR.RefreshData_ListBox.Selected(j) = True

                    End If

                Next

            End If

        Next

    End If

1 个答案:

答案 0 :(得分:1)

我的理解是,如果用户选择“全部”项目,则应取消选择任何其他项目。然后你可以沿着这些路线前进:

Private Sub RefreshData_ListBox_Change()
    Static bWorking As Boolean
    Dim lItem As Long
    Dim lUnselect As Long

    'Check the anti-recursion flag.        
    If Not bWorking Then
        For lItem = 0 To RefreshData_ListBox.ListCount - 1
            If RefreshData_ListBox.Selected(lItem) Then
                If StrComp(RefreshData_ListBox.List(lItem), "All", vbTextCompare) = 0 Then
                    'Manage recursion.
                    bWorking = True

                    For lUnselect = 0 To RefreshData_ListBox.ListCount - 1
                        If lUnselect <> lItem Then
                            RefreshData_ListBox.Selected(lUnselect) = False
                        End If
                    Next

                    bWorking = False
                End If
            End If
        Next
    End If
End Sub