vba Excel 2013 宏按多个选定值进行过滤

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24467023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:37:47  来源:igfitidea点击:

Excel 2013 macro to filter by multiple selected values

excelvba

提问by Rickson

I would like to implement a macro which does the following:

我想实现一个执行以下操作的宏:

If I select one or more cells belonging to the same column and activate the macro, then all rows which have not one of the selected values in the same column will be filtered out.

如果我选择属于同一列的一个或多个单元格并激活宏,则将过滤掉同一列中没有选定值之一的所有行。

I. e., if the macro would be activated in the following table:

即,如果宏将在下表中激活:

Original Table

原表

this would result in the following filtered table:

这将导致以下过滤表:

enter image description here

在此处输入图片说明

So far, I could manage to implement a piece of code which works fine if only one cell is selected:

到目前为止,我可以设法实现一段代码,如果只选择一个单元格,它就可以正常工作:

Range(ActiveCell.CurrentRegion.Address).AutoFilter Field:=ActiveCell.Column,Criteria1:=ActiveCell.Value

Could someone please help me to extend that code such that it is not limited to only one selected cell?

有人可以帮助我扩展该代码,使其不仅限于一个选定的单元格吗?

Any help is very appreciated!

非常感谢任何帮助!

回答by Alex P

Try this:

尝试这个:

Sub FilterMultipleCriteria()
    Dim filterRange As Range, filterValues() As Variant, cl As Range, i As Integer

    Set filterRange = Range("A1:C10") //Update the range as per your spreadsheet
    ReDim filterValues(Selection.Cells.Count - 1)
    i = 0

    For Each cl In Selection
        filterValues(i) = cl.Text
        i = i + 1
    Next cl

    filterRange.AutoFilter Field:=2, Criteria1:=filterValues, Operator:=xlFilterValues
End Sub

回答by Rickson

Thank you for your response. Based on your post I could come up with the following solution which seems to work fine:

谢谢您的答复。根据您的帖子,我可以提出以下似乎工作正常的解决方案:

Sub FilterMultipleCriteria()
    Dim filterValues() As Variant, cl As Range, i As Integer
    ReDim filterValues(Selection.Cells.Count - 1)
    i = 0
    For Each cl In Selection
        filterValues(i) = cl.Text
        i = i + 1
    Next cl
    Range(ActiveCell.CurrentRegion.Address).AutoFilter Field:=ActiveCell.Column, 
    Criteria1:=filterValues, Operator:=xlFilterValues
End Sub