简体   繁体   中英

How to check if a cell exists within a range in a different worksheet and then reference it

All I want to do is check if the Name (Cell B2) in Worksheet "Upload" is in the worksheet "Data" in column A, and if so return a message saying "Name already exists". Ideally I would like the macro to then take me to the row where the name exists. Any help would be appreciated. I've tried other threads and my code just falls over. So could you please add in a section that once locating if the duplicate exists in the "Data" sheet then it takes me into the "Data" sheet and locates it.

Function InRange(Range1 As Range, Range2 As Range) As Boolean
    ' returns True if Range1 is within Range2
    InRange = Not (Application.Intersect(Range1, Range2) Is Nothing)
End Function


Sub TestInRange()

Dim copySheet As Worksheet
Dim pasteSheet As Worksheet

Set copySheet = Worksheets("Upload")
Set pasteSheet = Worksheets("Data")

    If InRange(copySheet.Range("B2"), pasteSheet.Range("A2:A300")) Then
        ' code to handle that the cell is within the right range
        MsgBox "Name exists"
    Else
        ' code to handle that the cell is not within the right range
        MsgBox "Name does not exist"
    End If
End Sub
Sub test()

With Worksheets("Data").Range("a1:a500")
    Set c = .Find(Worksheets("Upload").Range("B2"), LookIn:=xlValues)
    If Not c Is Nothing Then
        MsgBox ("Name Exists")
            Else
        ' code to handle that the active cell is not within the right range
        MsgBox "Name does not exist"
    End If

    End With

End Sub

Actually quite straightforward

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM