我一直在寻找解决方案。虽然我得到一个相当模糊的“类型不匹配”错误,但我不确定它来自何处。
所以我的目标是创建一个通用函数,它从不同的工作表中获取两列,并验证一列中的值是否不显示在第二列中。
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
答案 0 :(得分:1)
Application.Match
行包含两个错误:
needle_sheet
之前添加Cells
,否则Excel会从activesheet
haystack_sheet
已经是工作表。此外,你必须限制你的循环(例如到UsedRange
),否则它将循环到工作表的最后。
试试这个:
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