EXCEL MACRO:检查值是否出现在其他工作表中

时间:2018-11-14 17:11:13

标签: excel vba excel-vba

这是新手,所以只给我一个问题,希望能有所帮助:)

基本上,我有一个列表,我想看看它是否出现在其他工作表之一中,而不是使用并返回取决于它所在工作表的字符串。 例如伪代码:

value = "Hi"
If value in sheet 2 Then
  return "Yes"
If value in sheet 3 Then
  return "TDB"
Else
  return " "

我到目前为止的代码

Public Function Check(product As String) As String

Dim BLRange As Range
Dim xlCell As Range
Dim BL As Worksheet
Dim TBDRange As Range
Dim TBD As Worksheet
Dim result As String

Set BL = ActiveWorkbook.Worksheets("Sheet2")
Set BLRange = BL.Range("A1:A1000")
Set TBD = ActiveWorkbook.Worksheets("Sheet3")
Set TBDRange = TBD.Range("A1:A1000")

For Each xlCell In BLRange
    If xlCell.Value = product Then
        Check = "Yes"
    End If
Next xlCell

For Each xlCell In TBDRange
    If xlCell.Value = product Then
        Check = "TBD"
    End If
Next xlCell

Check = ""
End Function

但是当我打电话给Check("Hi")时,我得到#VALUE!

有人看到我错了/得到建议吗?

谢谢

P.S压痕弄糟了

2 个答案:

答案 0 :(得分:3)

这是使用find的函数版本,例如提到的@urdearboy ...

Public Function Check(product As String) As String

    Dim BLRange As Range
    Dim TBDRange As Range
    Dim fndRng As Range

    With ActiveWorkbook
        Set BLRange = .Worksheets("Sheet2").Columns("A")
        Set TBDRange = .Worksheets("Sheet3").Columns("A")
    End With

    Set fndRng = BLRange.Find(product)
    If Not fndRng is Nothing Then Check = "Yes": Exit Function

    Set fndRng = TBDRange.Find(product)
    If Not fndRng is Nothing Then Check = "TBD": Exit Function

End Function

答案 1 :(得分:1)

尝试使用此代码(已经过测试并且可以正常工作)

Public Function Check(product As String) As String

Dim BLRange As Range
Dim BL As Worksheet
Dim TBDRange As Range
Dim TBD As Worksheet
Dim result As String

Set BL = ActiveWorkbook.Worksheets("Sheet2")
Set BLRange = BL.Range("A1:A1000")
Set TBD = ActiveWorkbook.Worksheets("Sheet3")
Set TBDRange = TBD.Range("A1:A1000")

Check = "none"

For Each xlCell In BLRange
 If xlCell.Text = product Then
    Check = "Yes"
    GoTo a
 End If
Next xlCell

For Each xlCell In TBDRange
 If xlCell.Text = product Then
    Check = "TBD"
    GoTo a
 End If
Next xlCell

Exit Function

a:


End Function