【问题标题】:Prevent Autofilter Criteria from changing from string to date防止自动筛选条件从字符串更改为日期
【发布时间】:2019-11-05 10:42:56
【问题描述】:

我有一些 5000 行的数据,其中一列代表一个组的大小。它们都是具有值范围的文本,例如:

"0 - 4", "5 - 9", "10 - 49", "50 - 99", "100 - 249", "250 or more"

这些都存储为文本。

我已经编写了一些 VBA 来使用自动过滤器来显示除我想要的项目之外的所有内容,以便可以删除其他行。喜欢:

activesheet.range("a1:a5000").autofilter field:=1, criteria1:="<>" & strValue

strValue 填充每个值并声明为字符串。

  • 一切正常,除非它到达"10 - 49"。它不会 显示时排除 "10 - 49"
  • 我可以手动复制该行为 -- 如果我使用自动过滤器 下拉列,选择文本Filters&gt;Does Not Equal,然后 然后选择"10 - 49" 的下拉选项(或直接输入)和 点击OK,它将不适用。它仍然显示 10 - 49 行。
  • 当我返回到 Text Filters&gt;Custom 过滤器时,它会显示 不等于18172

18172"Oct-1949" 的日期值。

即使我明确地将代码设置为:

activesheet.range("a1:a5000").autofilter field:=1, criteria1:="<>10 - 49"

它将 10 - 49 转换为日期值。如果您录制宏并通过自动筛选下拉菜单手动执行,它将在录制的代码中将标准 1 显示为 "&lt;&gt;Oct-1949"

我通过使用 criteria1:="&lt;&gt;*" &amp; strValue 让它工作,但这恰好适用于这些数据,但如果我在其中使用 10 - 49 的不同值可能无法工作。

所以我的问题是,有没有办法阻止它转换

"<>10 - 49"

"<>Oct-1949"

是否需要以某种方式对其进行转义以告诉它将其视为真实文本?或者这只是 Excel 的一个怪癖?它适用于criteria1:="=10 - 49"(即使在录制宏时)。

它发生在 Excel 2010、2013 和 2016 中。

【问题讨论】:

  • 列有文本格式吗?

标签: excel vba autofilter


【解决方案1】:

你会认为有办法的,尤其是10 - 49 中的空格。 直到/除非有人想出答案,你可以试试这个。

  • 创建要过滤的列中所有条目的唯一列表
  • 从该列表中排除 strvalue
  • 使用该唯一列表选择列中除strValue 之外的所有条目

下面只是一个示例,其中strValue 具有单个值。您应该能够使用该原理以其他方式应用该技术。

例如,使用整个列表填充集合,然后使用除 strValue 之外的所有内容填充 arrVals,这对于使用不同值填充 strValue 的情况可能会更好


Option Explicit
Sub filterTest()
    Dim R As Range, WS As Worksheet
    Const strValue As String = "10 - 49" 'value to exclude
    Dim colVals As Collection, vVals As Variant
    Dim arrVals() As String, I As Long

Set WS = Worksheets("sheet1")
With WS
    Set R = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With

WS.ShowAllData

'Get list of values to include
Set colVals = New Collection

'read the range into variant array for speed of execution
vVals = R.Offset(1, 0).Resize(R.Rows.Count - 1)

On Error Resume Next 'to skip the duplicates
    For I = 1 To UBound(vVals, 1)
        If Not vVals(I, 1) = strValue Then 'exclude if strValue
            colVals.Add vVals(I, 1), vVals(I, 1)
        End If
    Next I
On Error GoTo 0

ReDim arrVals(1 To colVals.Count)
For I = 1 To colVals.Count
    arrVals(I) = colVals(I)
Next I

R.AutoFilter field:=1, Criteria1:=arrVals, Operator:=xlFilterValues

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2020-12-09
    相关资源
    最近更新 更多