How to Compare Two Spreadsheets in Excel
This time a contribution from Yoav Ezer, the CEO of Cogniview.
Enjoy,
Diego
Being Microsoft Excel experts, the Cogniview team are often being emailed with tricky spreadsheet questions. A particularly interesting puzzle came through recently that we thought we would share with you here:
"Each month I have to compare two spreadsheets of products, each with the same header rows and same number of column. The number of rows are different each time.
Is it possible using Excel to compare these two lists and show only the differences? I would love it if we could create a macro to solve this??"
Seems like a cool challenge, and I would love to say I had a hand in coming up with the solution, but I am afraid it was the programming boffins at Cogniview who solved it!
The Solution
Several ideas were suggested and considered, including going through each sheet line by line using VB code. The problem always came when either or both sheets were really long and contained tons of data. Even on the fastest machine, it could be seen to grind to a halt.
The answer was to use Excel's built-in function RemoveDuplicates
to handle this. Unfortunately, that makes it a solution not available to users of older versions.
We need two source spreadsheets to compare, then a target spreadsheet for the results, as shown below.

Basically, this process requires our macro to perform two steps.
Step one, we copy the first sheet's data to a new sheet and put the second's data after it, then we use the RemoveDuplicates
function which removes the items from the second sheet that appear in the first.

In the second step, we do the same again in reverse order - copy the second sheet's data and then the first, and use RemoveDuplicates
again. The left over data in each case is the difference we need to display.

All we need to do then is present the results.

For each row, we state where the data was found.
The Macro
Most of the first routine sets everything up, copying the range of data as described above. The last two lines call our custom function LeaveOnlyDifferent
.
Sub CompareSheets()
' Merge into the current sheet
Dim sheetResult As Worksheet, Sheet1 As Worksheet, Sheet2 As Worksheet
Set sheetResult = ActiveSheet
' Clean merge sheet so we can work with it
If (MsgBox("This will erase all the data on the current sheet." & vbCrLf & _
"Do you wish to continue?", vbYesNo Or vbQuestion) <> vbYes) Then
Exit Sub
End If
sheetResult.UsedRange.Delete
' Ask for two sheets to compare
SelectSheet.SheetNames.Clear
For i = 1 To Worksheets.Count
SelectSheet.SheetNames.AddItem Worksheets(i).Name
Next
sFirstSheet = AskSheet
If (sFirstSheet = "") Then
Exit Sub
End If
Set Sheet1 = Sheets(sFirstSheet)
SelectSheetStart:
sSecondSheet = AskSheet
If (sSecondSheet = "") Then
Exit Sub
End If
If (sSecondSheet = sFirstSheet) Then
MsgBox "Please select different first and second sheets"
GoTo SelectSheetStart
End If
Set Sheet2 = Sheets(sSecondSheet)
' Find the column to use for marking
Dim sFromColumn As String
Dim nLastColumn As Integer
sTemp = Sheet1.UsedRange.Offset(1, 1).Address(True, True, 1)
sTemp = Mid(sTemp, InStr(sTemp, ":") + 1)
sFromColumn = Mid(sTemp, 2, InStrRev(sTemp, "$") - 2)
nLastColumn = Sheet1.UsedRange.Columns.Count
' Copy header
Sheet1.Range("A1:" & sFromColumn & "1").Copy sheetResult.Range("A1")
sheetResult.Range(sFromColumn & "1").Formula = "From Sheet"
' Compare stuff
LeaveOnlyDifferent Sheet2, Sheet1, sheetResult, sFromColumn, nLastColumn, 2
LeaveOnlyDifferent Sheet1, Sheet2, sheetResult, _
sFromColumn, nLastColumn, sheetResult.UsedRange.Rows.Count
End Sub
LeaveOnlyDifferent Function
This function is where the real solution lies, comparing and presenting the result. It accepts the sheets to compare and the destination, the columns and the first row. After copying the cells and removing duplicates, it copies the result to the top of the destination sheet.
Function LeaveOnlyDifferent(Sheet1 As Worksheet, Sheet2 As Worksheet, _
sheetResult As Worksheet, sFromColumn As String, nLastColumn As Integer, _
nFirstCompareRow As Integer)
' Copy first sheet data
nFirstDataRowCount = Sheet1.UsedRange.Rows.Count - 1
Sheet1.Range("A2:" & sFromColumn & _
(nFirstDataRowCount + 1)).Copy sheetResult.Range("A" & nFirstCompareRow)
' Copy second sheet data below the first
nStartOfSecondData = nFirstCompareRow + nFirstDataRowCount
Sheet2.Range("A2:" & sFromColumn & _
Sheet2.UsedRange.Rows.Count).Copy sheetResult.Range("A" & nStartOfSecondData)
' Remove duplicates
Dim arColumns() As Variant
ReDim arColumns(0 To nLastColumn - 1)
For i = 0 To nLastColumn - 1
arColumns(i) = CVar(i + 1)
Next
sheetResult.Range("A" & nFirstCompareRow & ":" & sFromColumn & _
sheetResult.UsedRange.Rows.Count).RemoveDuplicates arColumns, xlYes
' Mark the different data as coming from the proper sheet
nDiffRowCount = sheetResult.UsedRange.Rows.Count - nStartOfSecondData + 1
If (nDiffRowCount > 0) Then
sheetResult.Range(sFromColumn & nStartOfSecondData & ":" & sFromColumn & _
sheetResult.UsedRange.Rows.Count).Formula = "Found only on " & Sheet2.Name
' Copy it to the top
sheetResult.Range("A" & nStartOfSecondData & ":" & sFromColumn & _
sheetResult.UsedRange.Rows.Count).Copy sheetResult.Range("A" & nFirstCompareRow)
End If
' Delete all the rest
sheetResult.Range("A" & (nFirstCompareRow + nDiffRowCount) & ":" & _
sFromColumn & sheetResult.UsedRange.Rows.Count).Delete
End Function
Over to You
As mentioned earlier, there are many ways to solve this particular Excel challenge - how would you solve it? Could you see this solution as being useful? Please share your thoughts and experiences with us on Facebook or Twitter.
About the Author
This article was written by Yoav Ezer, the CEO of a company that creates PDF to XLS conversion software, called Cogniview.
Prior to that, he was the CEO of Nocturnus, a technology-centered software solution company.
发表评论
VSwFQK you employ a fantastic weblog here! want to earn some invite posts on my website?
sVWUsa in the next Very well written information. It will be valuable to anyone who employess it, including me. Keep doing what you are doing ? for sure i will check out more posts.
fMGk3M yay google is my queen helped me to find this great web site !.
Usa Online Casinos view of Three Gorges | Wonder Travel Blog
That is a really good tip particularly to those new to the blogosphere. Short but very precise information Thanks for sharing this one. A must read article!
Way cool! Some extremely valid points! I appreciate you writing this write-up and also the rest of the site is extremely good.
This particular blog is really cool as well as diverting. I have discovered a lot of handy tips out of this amazing blog. I ad love to come back again and again. Thanks a lot!
tаАабТТme now and finallаАааБТ got the braveаА аБТy
Wonderful beat ! I would like to apprentice while you amend
Im thankful for the article post.Really looking forward to read more. Keep writing.
Keep up the great work , I read few content on this site and I believe that your site is very interesting and contains sets of fantastic information.
It as difficult to find experienced people about this topic, however, you sound like you know what you are talking about! Thanks
Thanks for sharing, this is a fantastic article. Really Cool.
some times its a pain in the ass to read what people wrote but this website is very user genial !.
Modular Kitchens have changed the very idea of kitchen nowadays since it has provided household females with a comfortable yet a classy place in which they may invest their quality time and space.
On a geographic basis, michael kors canada is doing a wonderful job
Keep up the superb piece of work, I read few blog posts on this internet site and I believe that your blog is real interesting and contains lots of good information.
Im thankful for the blog.Thanks Again. Really Great.
Souls in the Waves Excellent Morning, I just stopped in to visit your site and assumed I would say I loved myself.
Mighty helpful mindset, appreciate your sharing with us.. So happy to get discovered this submit.. So pleased to possess identified this article.. certainly, investigation is having to pay off.
You can definitely see your enthusiasm in the work you write. The sector hopes for more passionate writers such as you who are not afraid to mention how they believe. All the time follow your heart.
You made some decent points there. I looked on the internet for the topic and found most individuals will consent with your blog.
Very good blog.Thanks Again. Really Cool.
Very good post, thanks so much for sharing. Do you have an RSS feed I can subscribe to?
Spot on with this write-up, I really believe that this web site needs a great deal more attention. I all probably be back again to read through more, thanks for the info!
I truly appreciate this post.Really looking forward to read more. Cool.
It as hard to discover knowledgeable folks on this subject, but you sound like you know what you are talking about! Thanks
JD Purity Most wanted Joomla design now available for Drupal
Thanks again for the article post.Thanks Again. Awesome.
Thanks for sharing, this is a fantastic article. Fantastic.
You are my breathing in, I have few web logs and very sporadically run out from to post.
Thanks for some other great article. Where else may anyone get that type of information in such a perfect method of writing? I have a presentation next week, and I am on the look for such information.
I truly appreciate this blog.Really thank you! Great.
Right away I am going to do my breakfast, after having my breakfast coming yet again to read additional news.
Thanks so much for the blog.Thanks Again. Cool.
I reckon something really special in this internet site.
You ave made some good points there. I looked on the net for additional information about the issue and found most people will go along with your views on this website.
8FMsCz Wow, this post is good, my sister is analyzing these kinds of things, so I am going to let know her.
Most of these new kitchen instruments can be stop due to the hard plastic covered train as motor. Each of them have their particular appropriate parts.
Yeah bookmaking this wasn at a risky conclusion outstanding post!.
I value the post.Thanks Again. Fantastic.
This actually is definitely helpful post. With thanks for the passion to present this kind of helpful suggestions here.
Say, you got a nice blog article.Thanks Again. Great.
What Follows Is A Approach That as Also Enabling bag-gurus To Expand
WONDERFUL Post.thanks for share..more wait.. aаАабТТаЂааАТаЂа
Say, you got a nice article.Thanks Again. Really Great.
This page really has all of the info I needed about this subject and didn at know who to ask.
Thank you ever so for you blog post.Really looking forward to read more. Awesome.
Say, you got a nice blog post.Really thank you! Will read on
wow, awesome article.Thanks Again. Great.