【问题标题】:Excel VBA multiple selection ListBox check if nothing is selectedExcel VBA多选列表框检查是否未选择任何内容
【发布时间】:2017-04-13 07:53:25
【问题描述】:

我正在尝试找出最好的方法,即如何使用 Excel ListBox 进行多项选择,并使用简单的 VBA 代码根据 ListBox 中选择的内容过滤多个工作表。

我现在拥有的代码如下。目前它几乎完全符合我的需要 - 检查工作表中是否有任何过滤器,如果有则清理它,然后过滤掉选定的值。但我还需要它做的是,根本没有选择任何值,它应该清洁 4 张过滤器并退出子。

问题是,如果我在未选择任何内容时尝试运行它,则会收到“无效过程”错误。我确实尝试添加一个 Else 语句和另一个 If 来检查 If .Listindex = -1,但是这两个选项都给出了完全相同的错误。 由于这需要是一个多选列表,我发现它还需要在检查是否未选择任何内容时循环,但又出现了同样的错误。

如何改进此代码并添加所需的功能?

Sub filter1()

Dim MyArray() As String
Dim Cnt As Long
Dim r As Long

Cnt = 0
With Me.ListBox1
    If .ListIndex <> -1 Then
        For r = 0 To .ListCount - 1
            If .Selected(r) Then
                Cnt = Cnt + 1
                ReDim Preserve MyArray(1 To Cnt)
                MyArray(Cnt) = .List(r)
            End If
        Next r
    End If
End With

With Sheet1
    If .FilterMode Then .ShowAllData
    .Range("A2:Y1037").AutoFilter field:=2, Criteria1:=MyArray, Operator:=xlFilterValues
End With

With Sheet3
    If .FilterMode Then .ShowAllData
    .Range("A2:AB1037").AutoFilter field:=2, Criteria1:=MyArray, Operator:=xlFilterValues
End With

With Sheet4
    If .FilterMode Then .ShowAllData
    .Range("A2:Z1037").AutoFilter field:=2, Criteria1:=MyArray, Operator:=xlFilterValues
End With

With Sheet5
    If .FilterMode Then .ShowAllData
    .Range("A2:Z1037").AutoFilter field:=2, Criteria1:=MyArray, Operator:=xlFilterValues
End With

End Sub

【问题讨论】:

    标签: vba excel listbox


    【解决方案1】:

    检查使用 Sheet1 行之前的 cnt 是否为 0,如果 cnt 为 0,则表示在 ListBox 中未选择任何内容,提示用户并使用如下所示的 exit sub...

    If cnt = 0 Then
        MsgBox "No item was selected in the ListBox." & _
                "Please select an item and then try again...", vbCritical, "No Item Selected"
        Exit Sub
    End If
    
    With Sheet1
    
    End With
    

    【讨论】:

    • 谢谢你,我采纳了你的建议,一切都很好!
    【解决方案2】:

    当您进行多选时,Listindex 没有帮助。因此,不要在循环后使用If .ListIndex &lt;&gt; -1 Then 检查cnt

    If cnt = 0      'nothing selected
         'code for no selection
    else
         'code with selection
    end if
    

    【讨论】:

      猜你喜欢
      • 2011-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      相关资源
      最近更新 更多