简体   繁体   English

带有动态字段列的 VBA 自动过滤器

[英]VBA Autofilter with dynamic field column

I made a code for filter by selected cell value, to create an quick access toolbar icon and make it faster to filter.我制作了一个代码,用于按选定的单元格值过滤,以创建一个快速访问工具栏图标并使其更快地过滤。 It worked perfectly when the filter started in column A. But some filters starts in columns B or C... and the value is filtered in another column, jumping the exact same number of blank columns that has no filter.当过滤器从 A 列开始时,它工作得很好。但是有些过滤器从 B 或 C 列开始......并且该值在另一列中被过滤,跳过完全相同数量的没有过滤器的空白列。 Do you guys know how to fix it?大家知道怎么修吗? How to get the VBA to return the field number?如何让VBA返回字段号?

Sub Filtro_Valor_Célula()
'Filtra a coluna pelo valor da célula selecionada
'


    Valor = ActiveCell.Value

    ActiveSheet.Range(ActiveSheet.AutoFilter.Range.Address).AutoFilter Field:=ActiveCell.Column, Criteria1:=Valor


End Sub

I'm having some trouble understanding your problem, but I think that your situation looks like this:我在理解您的问题时遇到了一些麻烦,但我认为您的情况如下所示:

在此处输入图片说明

In this example, if the given code is run we will filter on Column E instead of on Column C.在此示例中,如果运行给定的代码,我们将在 E 列而不是 C 列上进行过滤。

This is because the selected cell is in Column 3. But the field that we want to filter isn't the 3rd field in the AutoFilter -- it's the 1st field in the AutoFilter.这是因为所选单元格在第 3 列中。但我们要过滤的字段不是自动过滤器中的第三个字段——它是自动过滤器中的第一个字段。 It looks like the bit of code Field:=ActiveCell.Column isn't doing the right thing for us.看起来代码Field:=ActiveCell.Column对我们来说没有做正确的事情。

Try this instead:试试这个:

Sub Filtro_Valor_Célula()
'Filtra a coluna pelo valor da célula selecionada
'


    Valor = ActiveCell.Value
    FieldToFilter= ActiveCell.Column - ActiveSheet.AutoFilter.Range.Column + 1

    ActiveSheet.Range(ActiveSheet.AutoFilter.Range.Address).AutoFilter Field:=FieldToFilter, Criteria1:=Valor


End Sub

Here we take the position of the selected column (ActiveCell.Column) and subtract the column number that our AutoFilter begins in. We want to start counting from 1 and not zero, so we need to add 1 to the result.这里我们取所选列 (ActiveCell.Column) 的位置并减去我们的 AutoFilter 开始的列号。我们希望从 1 开始计数而不是从 0 开始,因此我们需要将 1 添加到结果中。

在此处输入图片说明

Hope it helps.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM