使用不同的工作表作为交叉引用来过滤工作表1中的值

时间:2017-01-19 06:41:58

标签: excel vba filter

我无法构思解决此问题的方法。我想基于工作表2中有效值的交叉引用过滤掉工作表1,F列的无效值。

我没有在Excel中使用过滤器的经验,但也许这是使用此功能的好机会。

困难在于表单1有多个试验(列c),每个试验都有多个有效值,如这些屏幕截图所示。

表1。 sheet 1

表2。 sheet 2

除了使用我不熟悉的过滤功能之外,我还在考虑创建一个字典对象并使用表1中的C列或表2中的A列作为键,但后来我不知道如何使程序检查多个值,而不使用一个大的长嵌套循环遍历工作表2的每个单元格以及工作表1中的列F.

我想要达到的基本任务是: For trial #, sheet 1, if column F =/= (a value in row #, sheet 2), then delete row.

更新 我试过这段代码,它在“for each”行上返回运行时1004应用程序或对象定义错误:

Sub RemoveNonMatch()

    Dim rngDel As Range, rw As Range

    For Each rw In ThisWorkbook.Sheets("full test").Range("B7:Q" & lastrow).Rows
        If Not IsMatch(rw.Cells(3).Value, rw.Cells(6).Value) Then
            If Not rngDel Is Nothing Then
                Set rngDel = Application.Union(rngDel, rw)
            Else
                Set rngDel = rw
            End If
        End If
    Next rw
    'remove any non-matches
    If Not rngDel Is Nothing Then rngDel.Delete
End Sub


Function IsMatch(TrialNum, AreaNum) As Boolean
    Dim t, a, rv
    rv = False
    With ThisWorkbook.Sheets("AOI crossref")
        'try to find TrialNum in the first column
        t = Application.Match(TrialNum, .Columns(1), 0)
        If Not IsError(t) Then
            'try to find AreaNum in the m'th row
            a = Application.Match(AreaNum, .Rows(t), 0)
            If Not IsError(a) Then rv = True 'match!
        End If
    End With
    IsMatch = rv
End Function

Here is a sample of the data I am using.

1 个答案:

答案 0 :(得分:1)

未测试:

Sub RemoveNonMatch()

    Dim rngDel As Range, rw As Range

    For Each rw In ThisWorkbook.Sheets("Sheet2").Range("A2I100").Rows 'or whatever...
        If Not IsMatch(rw.Cells(3).Value, rw.Cells(6).Value) Then
            If Not rngDel Is Nothing Then
                Set rngDel = Application.Union(rngDel, rw)
            Else
                Set rngDel = rw
            End If
        End If
    Next rw
    'remove any non-matches
    If Not rngDel Is Nothing Then rngDel.Delete
End Sub


Function IsMatch(TrialNum, AreaNum) As Boolean
    Dim t, a, rv
    rv = False
    With ThisWorkbook.Sheets("Sheet2")
        'try to find TrialNum in the first column
        t = Application.Match(TrialNum, .Columns(1), 0)
        If Not IsError(t) Then
            'try to find AreaNum in the m'th row
            a = Application.Match(AreaNum, .Rows(t), 0)
            If Not IsError(a) Then rv = True 'match!
        End If
    End With
    IsMatch = rv
End Function