Find If Value Exists on other Worksheet (Excel)

末鹿安然 提交于 2019-12-01 11:44:10

A very easy way is to declare the range that you want to search in and the value that you want to find.

Sub findValue()

    Dim xlRange As Range
    Dim xlCell As Range
    Dim xlSheet As Worksheet
    Dim valueToFind

    valueToFind = "MyValue"
    Set xlSheet = ActiveWorkbook.Worksheets("Sheet2")
    Set xlRange = xlSheet.Range("B1:B10")

    For Each xlCell In xlRange
        If xlCell.Value = valueToFind Then
            'Do Something
        End If
    Next xlCell

End Sub

I'm assuming that your range of ("A5:B5") is a merged cell because you indicated that it contained a single value. Merged cells can just be referenced by the "top left" cell within the merge (or at least that's how I think of it). So your merged range of ("A5:B5") can be referred to as just ("A5"). Anyway, here is a modified version of the method above that is more suited for your needs.

Sub findValue(ByVal valueToFind As String)

    Dim xlRange As Range
    Dim xlCell As Range
    Dim xlFormSheet As Worksheet
    Dim xlSamplesSheet As Worksheet
    Dim iLastRow As Integer
    Dim iRow As Integer
    Dim bFound As Boolean

    bFound = False
    Set xlFormSheet = ActiveWorkbook.Worksheets("FeedSampleForm")
    Set xlSamplesSheet = ActiveWorkbook.Worksheets("FeedSamples")

    iLastRow = xlSamplesSheet.Range("B1").End(xlDown).Row

    Set xlRange = xlsamplesheet.Range("B1:B" & iLastRow)

    For Each xlCell In xlRange
        If xlCell.value = valueToFind Then
            bFound = True '<-- The value was found
            iRow = xlCell.Row '<-- Here is the row that the value was found on
        End If

        If bFound Then Exit For '<-- Optional: Exit the for loop once the value is found the first time
    Next xlCell

End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!