排除不同工作表中的列值

Exclude column values in different sheets

我一直在寻找解决这个问题的方法。虽然我遇到了一个相当模糊的 'Type mismatch' 错误,但我不确定它来自哪里。

所以我的目标是创建一个通用函数,它从不同的工作表中获取两列,并验证一列中的值是否未显示在第二列中。

Public Function ExcludeColumns(needle_sheet As Worksheet, needle_column As Integer, haystack_sheet As Worksheet, haystack_column As Integer) As Boolean
    Dim var As Variant

    ' Loop column in needle sheet
    For Each rw In needle_sheet.Rows
        If needle_sheet.Cells(rw.Row, needle_column).Value = "" Then
            Exit For
        End If

var = Application.Match(Cells(rw.Row, needle_column).Value, Worksheets(haystack_sheet).Columns(haystack_column), 0)

        If Not IsError(var) Then
            MsgBox ("Value found")
        Else:
            MsgBox ("Value not found")
        End If
    Next rw
End Function

带有 Application.Match 的行包含两个错误:

  • 对于第一个参数,您必须提供单元格的来源信息。在 Cells 之前添加 needle_sheet,否则 Excel 将从 activesheet
  • 中获取它
  • 对于第二个参数,haystack_sheet已经是一个作品sheet。

此外,您必须限制循环(例如 UsedRange),否则它将循环到 sheet.

的最后

试试这个:

Public Function ExcludeColumns(needle_sheet As Worksheet, needle_column As Integer, haystack_sheet As Worksheet, haystack_column As Integer) As Boolean
Dim var As Variant, rw as Range

' Loop column in needle sheet
For Each rw In needle_sheet.UsedRange.Rows
    DoEvents

    If needle_sheet.Cells(rw.Row, needle_column).Value = "" Then
        Exit For
    End If

    var = Application.Match(needle_sheet.Cells(rw.Row, needle_column).Value, haystack_sheet.Columns(haystack_column), 0)

    If Not IsError(var) Then
        MsgBox ("Value found")
    Else:
        MsgBox ("Value not found")
    End If
Next rw
End Function