VBA: if any cell in range matches in another range?

JumboCactuar

Well-known Member
Joined
Nov 16, 2016
Messages
788
Office Version
  1. 365
Platform
  1. Windows
Hi,
I have some data we input into range C2:C20 and on button press the rows are pasted to the bottom of Sheet("Data")

What I'm wanting is if any of the values in C2:C20 are already in column C in the data sheet to display an error message Yes/No

Appreciate any help
 

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
you can make a dictionary of all the data in the data sheet column C then check if the new data exists on that sheet.

Something like the below (untested), but you should add in the sheet name where your new input data is.

Code:
Sub test()
Dim dic As Object, rng As Range, a As Variant, b
Set dic = CreateObject("Scripting.Dictionary")
a = Sheets("Data").Range("C2:C" & Sheets("Data").Range("C" & Rows.Count).End(xlUp).Row).Value
For i = 1 To UBound(a)
dic.Add a(i, 1), 1
Next


For Each rng In Range("C2:C20")
If dic.exists(rng.Value) Then
 b = MsgBox(rng.Value & " exists in Data sheet. Do you wish to proceed adding it?", vbYesNo)
If b = vbYes Then
Sheets("Data").Range("C" & Sheets("Data").Range("C" & Rows.Count).End(xlUp).Row + 1).Value = rng.Value
End If
Else
Sheets("Data").Range("C" & Sheets("Data").Range("C" & Rows.Count).End(xlUp).Row + 1).Value = rng.Value
End If
Next
End Sub
 
Last edited:
Upvote 0

Forum statistics

Threads
1,224,828
Messages
6,181,209
Members
453,022
Latest member
RobertV1609

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top