将自动过滤器中的值传递给vba中的组合框用户窗体

时间:2013-12-20 19:09:41

标签: excel vba excel-vba

我们可以通过将autofilter应用于特定的coloumn来传递值,并将过滤器值传递给excel vba中的combox userform

如果有可能,请提供相同的通用代码

编辑:OP评论中的代码:

Selection.AutoFilter 
Range("A:A").Select 
ActiveSheet.Range("A1:AL1000").AutoFilter Field:=1, Criteria1:="" & TextBox1.Text & "", Operator:=xlAnd 
Range("b1").Select 
Range("B:B").Copy 
'ActiveCell.CurrentRegion.Select 
'ActiveCell.CurrentRegion.Copy 
Sheets("Data").Select 
Range("B2").Select 
ActiveSheet.Paste

2 个答案:

答案 0 :(得分:0)

这是你在尝试什么?我已经对代码进行了评论,因此您在理解代码时不应该有任何问题。但如果你这样做,那么只需回发。

Option Explicit

Private Sub CommandButton1_Click()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim copyFrom As Range, aCell As Range
    Dim lRow As Long
    Dim strSearch As String

    Set wb = ThisWorkbook
    '~~> Set this to the worksheet where the autofilter is applied
    Set ws = wb.Worksheets("yourSheetName")

    '~~> Filter Column on
    strSearch = TextBox1.Text

    With ws
        '~~> Remove any filters
        .AutoFilterMode = False

        With .Range("A1:AL1000")
            .AutoFilter Field:=1, Criteria1:="=" & strSearch

            '~~> Identify the filtered range
            Set copyFrom = .Offset(1, 1).SpecialCells(xlCellTypeVisible)

            '~~> Add filtered values from Column 2 i.e from
            '~~> Col B to Combobox
            For Each aCell In copyFrom
                If aCell.Column = 2 Then _
                ComboBox1.AddItem aCell.Value
            Next
        End With

        '~~> Remove any filters
        .AutoFilterMode = False
    End With
End Sub

提示:您应该避免使用.Select/.Activate您可能希望看到THIS

答案 1 :(得分:0)

Private Sub CommandButton2_Click()

Dim wb As Workbook
Dim ws As Worksheet
Dim copyFrom As Range, aCell As Range
Dim lRow As Long
Dim strSearch As String

Set wb = ThisWorkbook
'~~> Set this to the worksheet where the autofilter is applied
Set ws = wb.Worksheets("MT")



With ws
    '~~> Remove any filters
    .AutoFilterMode = False

    With .Range("A1:AL1000")
        .AutoFilter Field:=1, Criteria1:="*" & TextBox1.Text & "*", Operator:=xlAnd

        '~~> Identify the filtered range
        Set copyFrom = .Offset(1, 1).SpecialCells(xlCellTypeVisible)

        '~~> Add filtered values from Column 2 i.e from
        '~~> Col B to Combobox
        For Each aCell In copyFrom
            If aCell.Column = 2 Then _
            ComboBox1.AddItem aCell.Value
        Next
    End With

    '~~> Remove any filters
    .AutoFilterMode = False
End With

End Sub

此代码正在过滤值但过滤后的值不在组合框中.. ComboBox1.AddItem aCell.Value此行给出错误