【问题标题】:Filtering Data from a specific column从特定列中过滤数据
【发布时间】:2014-07-01 17:13:28
【问题描述】:

大家好,我处于两难境地我正在尝试找出一种方法来过滤掉列字段中的某些数据我知道如何做到这一点,但我不知道要使用的正确语法。首先是表格,这是我要编写的代码结构。

for i=1 to length of column First Match
    for j=1 to length of column Second Match

    If ((value of the data in column First Match = 15) OR (value of the data in column FirstMatch = 1)) AND
       ((value of the data in column Second Match = 15) OR (value of the data in column Second Match = 1)) 
    Then
        Filter the data and append so the filtered datas are saved for both First Match and Second Match
    end if
    next
next

我正在尝试过滤掉 15 和 1 的数据,以便仅显示值为 0,2,3,4,5,6...14 的数据,例如 john 和steve 不会显示,因为第一个和第二个匹配字段都有 1 或 15,但其余数据将显示我的表单是拆分表单设置。

我的方法正确吗?


First Name    Last Name    First Match    Second Match
James         Matheson         0               2
Monroe        Labonson         4               3
Barack        Obama            2               5
Frederick     Douglas          3               4
Steve         MCGowan          1               1
John          Seals            15              15
Mike          Omalley          14              15



Set rs = CurrentDb.OpenRecordset("Table1")

Do While Not rs.EOF
If rs!Fields("First Match") > 1 And rs!Fields("First Match") < 15 And rs!Fields("Second Match") > 1 And rs!Fields("Second Match") < 15 Then

End If
Loop

【问题讨论】:

  • 我需要更多关于 ORs 和 ANDs 在你的逻辑中的顺序的信息。括号是你的朋友。
  • 现在问题更清楚了吗?
  • 是的。我正在努力。

标签: ms-access vba filtering


【解决方案1】:

有了更好的理解(我希望),我在 Access 中复制了您的数据并构建了一个查询,可以满足您的要求。最好的查看方法是创建一个新查询,而不是添加一个表,然后直接进入 SQL 视图。粘贴以下 SQL 语句(引号中的那个)并将matchFilter 替换为您的表名。

在您的事件代码中,您可以基于 SQL 创建记录集:

Dim sSQL as string, rs as Recordset

sSQL = "SELECT matchFilter.[First Name], matchFilter.[Last Name], matchFilter.[First Match], matchFilter.[Second Match] " & _
"FROM matchFilter " & _
"WHERE ((([First Match]<>1 And [First Match]<>15 And [Second Match]<>1 And [Second Match]<>15)=True))"
 Set rs = CurrentDB.OpenRecordset(sSQL)
 ' now do what you want

以下回答错误!

Dim rs as Recordset
Set rs = CurrentDB.OpenRecordset("yourTableName")
Do While Not rs.EOF
    If rs!Fields("col1") > 1 AND rs!Fields("col1") < 15 AND rs!Fields("col2") > 1 AND rs!Fields("col2") Then
        'do what you have to do with filtered out records
    End If
Loop

【讨论】:

  • 你能解释一下带有 rs 和 col1 和 col2 的代码行是你指定的实际字段名称还是列号。
  • 正确。 rs 是记录集(可能是您的表),col1col2 是您正在测试的字段名称。我假设(正确吗?)您只想包含 >=2 和
  • 我尝试在不添加任何过滤器的情况下运行它,在 Do while 所在的行显示“需要对象”
  • 我已经扩展了我的答案。您需要花一些时间查看 Access 中的开发人员帮助,以了解有关使用 VBA 的更多信息。 object required 消息是因为 rs 变量未初始化(Dim... 语句)和未赋值(Set... 语句)
  • 我再次尝试了代码,但这次它在我的表中找不到没有意义的字段。
【解决方案2】:

我找到了解决方案,显然这只是一个误解,因为我第一次尝试此代码时我认为它是错误的,但这是因为我的字段名称在我第一次编写它们之间没有空格。

Me.Filter = ""
Me.Filter = "[First Nam]<>'Jamie' AND [Last Nam]<>'Cartman'"
Me.FilterOn = True 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-18
    • 2020-09-11
    • 1970-01-01
    • 2016-04-03
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    相关资源
    最近更新 更多