VBA数组过滤函数问题:仅返回第一个结果

时间:2017-12-12 14:38:06

标签: excel vba excel-vba

我在使用VBA“过滤器”功能时遇到了一些问题。我试图使用多个后续过滤器逐步减少数组,包含我需要的值。但是,似乎只返回匹配“匹配”值的第一个元素,而不是后续的元素?

举一个例子,当运行下面的代码时,第二个'debug call'返回'1'但它应该返回'2'

Function FilterAnArray()

Dim names As Variant
names = Array("Ann Smith", "Barry Jones", "John Smith", "Stephen Brown", "Wilfred Cross")
Debug.Print UBound(names)

Dim smithNames As Variant
smithNames = Filter(names, "Smith")
Debug.Print UBound(smithNames)

End Function

版本信息e.t.c。

我正在运行Excel 2016,版本16.0.8730.2046 - 64位。 非常感谢任何有关此问题的帮助!

3 个答案:

答案 0 :(得分:3)

工作得很好。它返回1,因为你有两个史密斯:

enter image description here

smithNames的上限是1,因为它的数组是从0开始的。如果你想要数组元素的计数,并且你不喜欢UBound+1,你可以使用工作表函数:

Debug.Print WorksheetFunction.CountA(smithNames)

强烈不建议选项:

您可以考虑在模块顶部编写Option Base 1。然后阵列将基于1并且将是您期望的方式。在您的示例中,您了解为什么Option Base 1不可取。如果您拥有它,Names将为1 basedsmithNames将为0 based。这是因为数组的分配方式不同。

enter image description here enter image description here

答案 1 :(得分:2)

Ubound给予绑定绑定。当您使用基于0的数组时,您会得到5个条目的4个结果,以及2个条目的结果为1。

如果您想使用基于1的数组而不明确标注每个数组,请在模块的开头使用Option Base 1

答案 2 :(得分:0)

如何检查您应该获得多少结果然后打印它们,例如:

Sub foo()
Dim val As Variant
Dim names As Variant
Dim post As Variant
names = Array("Ann Smith", "Barry Jones", "John Smith", "Stephen Brown", "Wilfred Cross")
Debug.Print UBound(names)

Dim smithNames As Variant
smithNames = Filter(names, "Smith")

pos = Application.Match(smithNames, names, False) 'find how many values match "Smith"

If Not IsError(pos) Then
    For x = LBound(pos) To UBound(pos)
        Debug.Print pos(x)
    Next x
Else
   MsgBox val & " not found!"
End If
End Sub