473,668 Members | 2,446 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Excel: VBA code that look for values and compare it

5 New Member
Hi all,

I need some help with a VBA code. I have tried differents codes that i fund in the forum but they didn t match with what i m looking for. So i will explain what i have , what i need and what i expect.

I have a workbook with 2 sheets (Sheet1 , Sheet2). Both sheets have values in columns A to F. (A:F). Values Start at A2. B2..... etc in both sheets, and end up sometimes at A1000. B1000. ... etc.

What i want to do:
I need a macro that look for the values that are in Sheet 1 and NOT in Sheet 2.
And also the macro will look for the values that are in Sheet2 and NOY in Sheet1.

What i need:
Is that the result appears in a new workbook ( or in Sheet3), and that the result appears in columns A and B. In column Ait will display the values that are in Sheet1 and NOT in Sheet2. And in Column B the values that are in Sheet2 and NOT in Sheet 1.

So if anyone can help me it would be great because i really don t know how to do this.

Thanks

if anyone has a different idea of displaying results i m open to your advices.
Nov 25 '09 #1
14 20652
ADezii
8,834 Recognized Expert Expert
Here is the basic Logic that you would need to compare every Value in Sheet1 within the Range $A$2:$F$1000 to every Value in Sheet2 for the same Range. Keep in mind that this is a very CPU intensive process since it involves approximately 36,000,000 iterations of the Nested Loops (approximately 2 minutes).
Expand|Select|Wrap|Line Numbers
  1. Dim rng_1 As Range
  2. Dim rng_2 As Range
  3. Dim rngRef_1 As Range
  4. Dim rngRef_2 As Range
  5.  
  6.  
  7. Set rng_1 = Worksheets("Sheet1").Range("$A$2:$F$1000")
  8. Set rng_2 = Worksheets("Sheet2").Range("$A$2:$F$1000")
  9.  
  10. For Each rngRef_1 In rng_1
  11.   For Each rngRef_2 In rng_2
  12.     If rngRef_1.Value <> "" Then
  13.       If rngRef_1.Value = rngRef_2.Value Then
  14.         Debug.Print "Value " & rngRef_1.Value & " in Sheet1 found at " & _
  15.                      rngRef_2.Address & " in Sheet2"
  16.       End If
  17.     End If
  18.   Next
  19. Next
Sample OUTPUT:
Expand|Select|Wrap|Line Numbers
  1. Value 66 in Sheet1 found at $D$31 in Sheet2
  2. Value 77 in Sheet1 found at $C$16 in Sheet2
  3. Value 9998887 in Sheet1 found at $F$100 in Sheet2
  4. Value 3456 in Sheet1 found at $C$7 in Sheet2
  5. Value 66 in Sheet1 found at $D$31 in Sheet2
  6. Value 77 in Sheet1 found at $C$16 in Sheet2
  7. Value 9998887 in Sheet1 found at $F$100 in Sheet2
  8. Value 3456 in Sheet1 found at $C$7 in Sheet2
  9. Value 66 in Sheet1 found at $D$31 in Sheet2
  10. Value 77 in Sheet1 found at $C$16 in Sheet2
  11. Value 9998887 in Sheet1 found at $F$100 in Sheet2
  12. Value 3456 in Sheet1 found at $C$7 in Sheet2
  13. Value Way down here! in Sheet1 found at $E$999 in Sheet2
Nov 26 '09 #2
moutoncito
5 New Member
Hello ADezii :

I tried to use the macro that you send me, and i have no results displays !!!
I don t know how to do?? And i didn t understood the last part of your code??

OUTPUT
Value 66 in Sheet1 found at $D$31 in Sheet2
Value 77 in Sheet1 found at $C$16 in Sheet2
Value 9998887 in Sheet1 found at $F$100 in Sheet2
Value 3456 in Sheet1 found at $C$7 in Sheet2
Value 66 in Sheet1 found at $D$31 in Sheet2
Value 77 in Sheet1 found at $C$16 in Sheet2
Value 9998887 in Sheet1 found at $F$100 in Sheet2
Value 3456 in Sheet1 found at $C$7 in Sheet2
Value 66 in Sheet1 found at $D$31 in Sheet2
Value 77 in Sheet1 found at $C$16 in Sheet2
Value 9998887 in Sheet1 found at $F$100 in Sheet2
Value 3456 in Sheet1 found at $C$7 in Sheet2
Value Way down here! in Sheet1 found at $E$999 in Sheet2

How does it works??

Thanks for the help
Nov 26 '09 #3
ADezii
8,834 Recognized Expert Expert
One question at a time.
  1. Press the ALT+F11 Key Combiniation to Open the VBA Code Window.
  2. If the Immediate Window is not already Open, press CTRL+G.
  3. The results of the comparison will be in this Window.
Nov 27 '09 #4
ADezii
8,834 Recognized Expert Expert
I've taken the liberty to modify the Code and output the Results (Matches) to the 1st Column of Sheet3. Just make sure that you have 3 Worksheets named: Sheet1, Sheet2, and Sheet3 in order for the Revised Code to work properly.
Expand|Select|Wrap|Line Numbers
  1. Dim rng_1 As Range
  2. Dim rng_2 As Range
  3. Dim rngRef_1 As Range
  4. Dim rngRef_2 As Range
  5. Dim intRowNum As Integer
  6.  
  7. Worksheets("Sheet3").Range("A1:A1000").ClearContents
  8.  
  9. Set rng_1 = Worksheets("Sheet1").Range("$A$2:$F$1000")
  10. Set rng_2 = Worksheets("Sheet2").Range("$A$2:$F$1000")
  11.  
  12. For Each rngRef_1 In rng_1
  13.   For Each rngRef_2 In rng_2
  14.     If rngRef_1.Value <> "" Then
  15.       If rngRef_1.Value = rngRef_2.Value Then
  16.         intRowNum = intRowNum + 1
  17.         Worksheets("Sheet3").Cells(intRowNum, 1).Value = "Match# " & intRowNum & ": " & _
  18.                     "Value " & rngRef_1.Value & " in Sheet1 found at " & _
  19.                      rngRef_2.Address & " in Sheet2"
  20.       End If
  21.     End If
  22.   Next
  23. Next
  24.  
  25. 'Allow for 1,000 Matches
  26. Worksheets("Sheet3").Range("A1:A1000").Columns.AutoFit
Nov 27 '09 #5
NeoPa
32,568 Recognized Expert Moderator MVP
I would consider using VLookup(...) for this task. It is a built-in Excel function that you can use in a formula that can be copied to all the relevant cells in Sheet3. I have included a document as an attachment that I set up for some of my users at work on how they can use this most powerful of functions. I include the text part of it here to be visible.

VLookUp(A, B, C, D)

VlookUp or Vertical LookUp is a function that enables Excel to 'Find' related items from within a range stored elsewhere. Elsewhere can mean another excel workbook on another PC, but can also mean a range in the current worksheet.

In any Range reference in Excel, a '$' preceeding an element of the address, simply tells Excel not to be clever when copying or dragging the formula to other cells. Notice the formulas displayed in column B below: First B1 is created, then that cell is copied and pasted, or dragged down over, the other cells. Notice the only item that changes is the number (Row reference) after $A.
  1. This is the item to search for and is often a cell reference. The '$' is usually required here for the column letter but rarely for the Row number.
  2. This is a reference to the range being searched. This is almost always fully referenced with '$'s.

    If it is a requirement to refer to ranges in other worksheets or even other workbooks, the format for each of these is illustrated in cells E1 & E3 below respectively. For space reasons, the range in Book2 starts at B3 rather than at E5, but '[Book1]Sheet 2' has the data in the same place as Sheet1 (E5:F9). Basically, a worksheet reference preceeds the cell part with a '!' separating them. Any complicated name (reserved word or containing unusual characters including spaces) requires singe quotes (') around it - Sheet2!$A$1:$C$ 9 but 'Sheet 2'!$A$1:$C$9. A workbook reference preceeds the worksheet reference and is surrounded in [] brackets. If (')s required in sheet name then the workbook reference follows the first (') - '[Book2]Sheet 2'!$A$1:$C$9.
  3. This is the column to display if a match is found. In the example below, the words (Abacus; Broadcast; ...) are found in column F, but in column 2 from the left of the range. Column C shows the results displayed when the formula in Column B is used.
  4. This indicates to Excel how it should treat items where a match isn't found :
    True (or non-zero) indicates it expects an ordered table and it will return the next item in the list after the point this item would have been. This is never used for simply finding items in a list. This would be used by accountants sometimes.

    False (or zero) will only find exact matches. Any item not found would return a #N/A value (See C4 below) which can be detected by using the ISNA() function.

NB. The quotes in the word document are converted by Word. They should all read (').
Attached Files
File Type: zip VLookUp.Zip (35.8 KB, 491 views)
Nov 29 '09 #6
ADezii
8,834 Recognized Expert Expert
Hello NeoPa, forgive my ignorance, but it is my understanding that VLookup() will find every Value defined in a Single Column of an Array within a Range/List. How can this be applied when searching for every conceivable Match within a Range defined in Sheet1 (A2:F1000) against an identical Range in Sheet2? Checking every Value in Sheet1 against every Value in Sheet2 would involve , (5,994 * 5,994), or 35,928,036 individual checks for equality. Take care.
Nov 29 '09 #7
NeoPa
32,568 Recognized Expert Moderator MVP
VLookup() will handle checking all the values in a column, so if the OP indeed meant that each value of each column is treated altogether like a single list (which isn't so clear from the explanation), then a formula including VLookups is still likely to be an efficient solution.

If however, the values in column A are the only ones that need checking (and there is nothing explicit to say the columns are independant values), then it's only one.

Obviously we don't have all the facts, but assuming the data is held in up to a thousand rows and all the data is to be treated as similar, then it would be common sense, and really quite easy, to produce a set (or two) of data first where all is contained in a single column. From there it would be as simple as it should be.
Nov 29 '09 #8
ADezii
8,834 Recognized Expert Expert
Thanks for the explanation. I've never actually used it, so I was indeed curious.
Nov 29 '09 #9
NeoPa
32,568 Recognized Expert Moderator MVP
No need for explanations ADezii. It was a perfectly reasonable question.

I would say though, if you are doing any sort of work in Excel using large sets of data, VLookup() is a skill you should certainly gain.
Nov 29 '09 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

4
8456
by: IMS.Rushikesh | last post by:
Hi All, I am trying to execute below code but it gives me an COMException ///// Code Start //// public string GetName(Excel.Range range) { try { if (range.Name != null)
6
4060
by: Elena | last post by:
I'm trying to export data to an Excel worksheet. I can export the data in the cell values perfectly. I need the code to change a header and footer for the worksheet, not for the columns. Is this possible? If so, I really need the code immediately. Thank you, Elena
0
3665
by: vinidimple | last post by:
Hi i have a serious problem while i was working in Excel.I want to fetch columns from an excel worksheet and i need to compare it with an sql querry fields,so i tried to open an excle worksheet first.. Unfortunately my code was throwing error like
2
2883
by: sherifffruitfly | last post by:
Hi, I'm using an adaptation of excel-reading code that's all over the internet - I don't much like or understand it, but it has worked for me in the past.... beggars can't be choosers... : Excel.Application excelObj = new Excel.Application(); Excel.Workbook theWorkbook = excelObj.Workbooks.Open(path+filename, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false,
16
2689
by: alexia.bee | last post by:
Hi all, In some weird reason, excel instance won;t die if i remove the comment from 4 lines of setting values into struct. here is a snipcode public System.Collections.Generic.List<frmMain.sDBTest> LoadTestSet(string TestSetFile, System.Collections.Generic.List<frmMain.sDBTestDBviewList)
11
5763
by: bbasberg | last post by:
Hello, I have been struggling with this problem for DAYS and have googled my heart out as well as reading any books I could get my hands on but I cannot find any specific references to my problem. I have been able to successfully loop through a directory reading spreadsheets that insert records into an Access database. The spreadsheets in said directory are all of the same format but have different values in the cells. It's when I turned...
1
10490
by: CoolFactor | last post by:
MY CODE IS NEAR THE BOTTOM I want to export this Access query into Excel using a command button on an Access form in the following way I describe below. Below you will find the simple query I am trying to export to Excel using a command in an Access Form. RowID strFY AccountID CostElementWBS 1 2008 1 7 2 2008 1 7 I want to...
6
1727
by: Nimion | last post by:
For work I've been tasked with creating some verification programs. So I thought best way to do this is to take their excel sheet and compare the data... I've been able to open the excel sheet and place it into a DataGridView, but now I'm stumped on how I actually use the data Im seeing... I.E - The sheet has 2 columns (min) and (max) with about 20 rows of values... I want to be able to compare the data a user inputs against these two...
2
6028
by: jumperbl | last post by:
I want to look at two columns lets say B1 to B8 and C1 to C8. I want to compare those ranges and if the columns don't match i want to color the cell. Here is how much i have figured out. import win32com.client xlApp = win32com.client.Dispatch("Excel.Application") xlApp.Visible=1 xlWb = xlApp.Workbooks.Open(r"C:\Template_Rev_3.2.xls") print xlApp.Worksheets("sheet1").Name
0
8459
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8889
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8790
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8572
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
4202
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4372
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2782
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2017
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1779
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.