VBA是否可以将Dictionary / Collection传递给自动过滤器?

时间:2014-06-20 14:40:14

标签: excel vba dictionary collections autofilter

我们的想法是创建一个变量,以保存之前使用宏所做的更改。我有一个userform,它从一个范围中提取值并在列表框中填充唯一值。然后,我希望能够将选定的值添加到我的字典/集合中并保存更改。完成所有必要的更改后,宏应使用字典变量作为自动过滤器的条件。

我的问题有两个问题,我应该用什么课来完成这个?如何使用此变量自动过滤我的工作表? Userform代码如下:

第一位代码用于"添加"命令按钮。它应该在列表框中取选择的值并将它们添加到标题为" Market"的字典中。之后的代码从最近打开的excel工作簿中提取值,在列表框中显示唯一值。 Listbox2包含以前使用宏的所有先前值。我想添加一个"删除"按钮指向userform以在必要时整理列表。下面的两个公共变量实际上位于主宏模块上,这样我就可以在userform停止运行后将值存储在字典中。

Private Sub CommandButton1_Click()
Dim i As Long

For i = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected(i) = True Then
        Market.Add ListBox1.List(i)
        Set Market = New Collection
    End If
Next


End Sub

Private Sub UserForm_Initialize()

Dim myList As Collection
 Dim myRange As Range
 Dim ws As Worksheet
 Dim myVal As Variant
 Dim Col As Integer

 Set ws = ActiveWorkbook.Sheets("Daily Unconfirmed")
 Col = WorksheetFunction.Match("Marketer", ws.Range("3:3"), 0)
 Set myRange = ws.Range(Cells(4, Col), Cells(4, Col).End(xlDown))
 Set myList = New Collection
 On Error Resume Next

 For Each mycell In myRange.Cells
     myList.Add mycell.Value, CStr(mycell.Value)
 Next mycell
 On Error GoTo 0

 For Each myVal In myList
     Me.ListBox1.AddItem myVal
 Next myVal

公共项目As Variant 公共市场作为集合

Market.Add "Al D"
Market.Add "B Collins"
Market.Add "B G"
Market.Add "C Huter"

For Each item In Market
    Me.ListBox2.AddItem item
Next item

End Sub

1 个答案:

答案 0 :(得分:0)

由于 AutoFilter 数组运行,我会动态构建数组并在过滤子中使用它:

Dim ary()

Sub MAIN()
    Call BuildDynamicArray
    Call FilterMyData
End Sub

Sub BuildDynamicArray()
    Dim inString As String
    i = 1
    While 1 = 1
        x = Application.InputBox(Prompt:="Enter a value", Type:=2)
        If x = False Then GoTo out
        ReDim Preserve ary(1 To i)
        ary(i) = x
        i = i + 1
    Wend
out:
End Sub

Sub FilterMyData()
    ActiveSheet.Range("$A$1:$A$10").AutoFilter Field:=1, Criteria1:=ary, Operator:=xlFilterValues
End Sub