VBA:计算过滤器中选择的不同项目的数量

时间:2015-06-24 13:32:52

标签: excel vba excel-vba if-statement filter

在Excel中,我在标题上有一个过滤器,此过滤器允许用户选择不同的区域并显示与所选区域匹配的记录。我有以下代码,然后显示在筛选器中选择的值:

Dim ftrRegion As Filter
On Error GoTo stopError
Set ftrArea = ActiveSheet.AutoFilter.Filters(2)
Set ftrRegion = ActiveSheet.AutoFilter.Filters(1)

If ftrRegion.On Then
    Application.EnableEvents = False
    Debug.Print ftrRegion.Criteria1
    Range("E206").Value = Mid$(ftrRegion.Criteria1, 2)
    Range("F201").Value = "Region" & " " & Mid$(ftrRegion.Criteria1, 2)
Else
    Range("E206").Value = ""
End If

但问题是,如果用户选择了多个值,则整个过程不起作用,所以我想要的是一种计算用户在过滤器中选择的值的方法,如果它只是1然后通过if语句应用此代码。有人可以帮忙。

2 个答案:

答案 0 :(得分:3)

更改

If ftrRegion.On Then

If ftrRegion.On And ftrRegion.Count = 1 Then

答案 1 :(得分:0)

我没有使用最新版本的Office对此进行测试,但它可能有所帮助:

Function GetFilterSettings(oFilter As Filter) As String
   Dim sTemp           As String
   With oFilter
      If .On Then
         If IsArray(.Criteria1) Then
            sTemp = Join(.Criteria1, ", ")
         Else
            Select Case .Operator
               Case xlAnd
                  sTemp = .Criteria1
                  If Len(.Criteria2) > 0 Then _
                     sTemp = sTemp & " and " & .Criteria2
               Case xlBottom10Percent
                  sTemp = "Bottom n% - effectively" & .Criteria1
               Case xlTop10Items
                  sTemp = "Top n items - effectively " & .Criteria1
               Case xlBottom10Items
                  sTemp = "Bottom n items - effectively " & .Criteria1
               Case xlOr
                  sTemp = .Criteria1
                  If Len(.Criteria2) > 0 Then _
                     sTemp = sTemp & " or " & .Criteria2
               Case xlTop10Percent
                  sTemp = "Top n% - effectively " & .Criteria1
            End Select
         End If
      Else
         sTemp = "Off"
      End If
   End With
   GetFilterSettings = sTemp

End Function

因此,在普通模块中,您的代码将变为:

Dim ftrRegion As Filter
On Error GoTo stopError
Set ftrArea = ActiveSheet.AutoFilter.Filters(2)
Set ftrRegion = ActiveSheet.AutoFilter.Filters(1)

    Application.EnableEvents = False
    Range("E206").Value = GetFilterSettings(ftrArea)
    Range("F201").Value = "Region " & GetFilterSettings(ftrRegion)