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

JumboCactuar

Well-known Member
Joined
Nov 16, 2016
Messages
785
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

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
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,216,124
Messages
6,128,987
Members
449,480
Latest member
yesitisasport

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