VBA用多个复选框显示结果" True"条件

时间:2017-07-21 07:09:41

标签: excel vba excel-vba

我设计了一个带有多个选项的列表框的useform。

列表框中填充了“位置”。例如:德国,美国等。

如果Checkbox"德国"是的,那么它应该在我的表格中过滤德国的结果"结果"在列" L"。如果选中Checkbox" GErmany和USA"然后我想在我的工作表中为两个位置过滤结果。

通过互联网浏览,我找到了这样的代码:这适用于Checkbox,我应该如何修改具有多个选项的Listbox?

Private Sub Filter()

Dim Ws As Worksheet
Dim strCriteria() As String
Dim arrIdx As Integer

Dim cBox As Control

arrIdx = 0
For Each cBox In Me.Controls
    If TypeName(cBox) = "CheckBox" Then
        If cBox.Value = True Then
            ReDim Preserve strCriteria(0 To arrIdx)
            strCriteria(arrIdx) = cBox.Caption
            arrIdx = arrIdx + 1
        End If
    End If
Next cBox

Set Ws = ThisWorkbook.Sheets("Result")
If arrIdx = 0 Then
    Ws.UsedRange.AutoFilter
Else
    Ws.Range("A:R").AutoFilter Field:=12, Criteria1:=Array(strCriteria), Operator:=xlFilterValues
End If

End Sub

这适用于Checkbox,如何使用多个选项(如下面的图像

)为列表框修改此功能

This is how I have my listbox, designed with Checkbox.

任何领导都会有所帮助

4 个答案:

答案 0 :(得分:2)

这可能对您有所帮助

With ListBox1
For x = 0 To .ListCount - 1
    If .Selected(x) Then
        temp = temp & Chr(10) & .List(x)
    End If
Next
End With

MsgBox temp & " is selected"

答案 1 :(得分:2)

尝试

Dim strCriteria() As String, i As Integer, arrIdx As Integer
ReDim strCriteria(0 To Me.listBoxCountries.ListCount-1)

For i = 0 To Me.listBoxCountries.ListCount - 1
    If Me.listBoxCountries.Selected(i) Then
        strCriteria(arrIdx) = Me.listBoxCountries.List(i)
        arrIdx = arrIdx + 1
    End If
Next i

If arrIdx = 0 Then
    Ws.UsedRange.AutoFilter
Else
    ReDim preserve strCriteria(arrIdx - 1)
    Ws.Range("A:R").AutoFilter Field:=12, Criteria1:=Array(strCriteria), Operator:=xlFilterValues
End If

答案 2 :(得分:0)

如果您熟悉Change上的listbox活动,请查看教程here。只有麻烦才能从listbox

中选择多个项目

答案 3 :(得分:0)

在Fun Thomas的帮助下,我编辑了几行代码,它符合我的要求。

这是代码。

Private Sub DoFilter34()
Dim ws As Worksheet
Dim strCriteria() As String, i As Integer, arrIdx As Integer
ReDim Preserve strCriteria(0 To arrIdx)

arrIdx = 0
For i = 0 To Me.ListBox1.ListCount - 1
    If Me.ListBox1.Selected(i) Then
    ReDim Preserve strCriteria(0 To arrIdx)
        strCriteria(arrIdx) = Me.ListBox1.List(i)
        arrIdx = arrIdx + 1
    End If
Next i
Set ws = Sheets("Result")
If arrIdx = 0 Then
ws.UsedRange.AutoFilter
Else
    ws.Range("A:R").AutoFilter Field:=12, Criteria1:=Array(strCriteria), Operator:=xlFilterValues
End If
End Sub