473,387 Members | 1,515 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Compare 2 worksheets in Excel and delete rows not contained in both.

Compare Current Year Worksheet with Previous Year Worksheet and if SSN exists in Current Year Worksheet & Not in Previous Year - Copy this Row from Current Year Worksheet & Paste into Previous Year Worksheet

Compare Previous Year Worksheet with Current Year Worksheet and if SSN exists in Previous Year Worksheet & Not in Current Year Worksheet - Delete this Row out of Previous Year Worksheet - THIS IS WHERE I'M HAVING TROUBLE.


This is the code I have so far. I just don't know how to delete the row.


Sub CompareWorksheets()
Dim wsCurrentYear As Worksheet, wsPreviousYear As Worksheet
Dim rngCurrent As Range, rngPrevious As Range
Dim LastRow As Long
Dim res As Variant

Set wsCurrentYear = Worksheets("CurrentYear")
Set wsPreviousYear = Worksheets("PreviousYear")

'---- Current Year Worksheet
With wsCurrentYear
wsCurrentYearLastRow = .Cells(Rows.Count, 1).End(xlUp).Row
Set rngCurrent = .Range("a2:a" & wsCurrentYearLastRow)
End With

'---- Previous Year Worksheet
With wsPreviousYear
wsPreviousYearLastRow = .Cells(Rows.Count, 1).End(xlUp).Row
Set rngPrevious = .Range("a8:a" & wsPreviousYearLastRow)
Set rngDelete = .Range("q8:q" & wsPreviousYearLastRow)
End With


'---- Compare Current Year Worksheet with Previous Year Worksheet
'---- If SSN exists in Current Year Worksheet & Not in Previous Year -
'---- Copy this Row from Current Year Worksheet & Paste into Previous Year Worksheet
wsPreviousYearNextRow = wsPreviousYearLastRow + 1
For Each cell In rngCurrent
res = Application.Match(cell, rngPrevious, 0)
If IsError(res) Then ' Add to end of Previous Year
wsPreviousYear.Cells(wsPreviousYearNextRow, "A") = cell.Value
wsPreviousYear.Cells(wsPreviousYearNextRow, "R") = "Added"
wsPreviousYearNextRow = wsPreviousYearNextRow + 1
End If
Next cell


'---- Compare Previous Year Worksheet with Current Year Worksheet
'---- If SSN exists in Previous Year Worksheet & Not in Current Year Worksheet -
'---- Delete this Row out of Previous Year Worksheet
For Each cell In rngPrevious
res = Application.Match(cell, rngCurrent, 0)
If IsError(res) Then
'---- IF IN PREVIOUS YEAR AND NOT IN CURRENT YEAR, INSERT THE WORD
'---- "DELETE" IN COLUMN Q SO THAT ROW CAN BE DELETED
wsPreviousYear.Cells(cell.Row, "Q") = "Delete"
'---- I WOULD REALLY RATHER DELETE THE ROW HERE IN LIEU OF ADDING THE
'---- WORD "DELETE" TO THE ROW & COLUMN Q
End If
Next cell

'---- SINCE I DIDN'T KNOW HOW TO GET IT TO DELETE THE ROW ABOVE, I TRIED
'---- DELETING THE ROWS THAT HAVE THE WORD DELETE ADDED TO COLUMN Q
With rngDelete
Set c = .Find("Delete", LookIn:=xlValues)
If Not c Is Nothing Then
firstAddress = c.Address
Do
'---- Change the word "Delete" to "Delete Row" just to see if this is working properly!

'---- IF I TRY TO DELETE THE ROWS (IN LIEU OF CHANGE THE VALUE TO "DELETE ROW"
'---- THEN IT BOMBS ON - Set c = FindNext(c)

c.Value = "Delete Row"
Set c = .FindNext(c)
Loop While Not c Is Nothing And c.Address <> firstAddress
End If
End With

End Sub

I REALLY NEED YOUR HELP ASAP.

THANKS.
Nov 30 '06 #1
13 6920
Killer42
8,435 Expert 8TB
I don't recall how to delete a row either, just at the moment. But a good way to check these sort of things is to start recording a new macro, do the operation yourself, then grab the code which was generated.
Dec 1 '06 #2
Killer42
8,435 Expert 8TB
Sorry, I didn't realise you had more comments about the problem in your code. I haven't had a chance to read the whole thing yet (maybe at lunch time).

One question, though. When you refer to "deleting" a row, do you mean to literally delete the row, or simply blank out the data on that row?
Dec 1 '06 #3
Yes, I mean to literally delete a row.

I did finally get things to work, partially.

I replaced the following line of code:
wsPreviousYear.Cells(cell.Row, "Q") = "Delete"
With:
wsPreviousYear.Rows(cell.Row).Delete

This did actually delete the rows, but there is a problem.

If the rows are in consecutive rows, it skips every other row.

Example: If it should delete rows 21, 25, 38, 45, 50, 51, 52, 53, 54, 55 & 56
It deletes rows 21, 25, 38, 45, 50, 52, 54, & 56, but does NOT delete rows 51, 53 and 55.

It works fine when I add the word "Delete" to row Q, but does not work fine when actually deleting the row. I thought it had something to do with it actually deleting the row, that it moved down a row and was not looking in that particular row, so I added the following code, but that didn't make a difference either.

For Each cell In rngPrevious
res = Application.Match(cell, rngCurrent, 0)
If IsError(res) Then
Dim ReturnPreviousRow
ReturnPreviousRow = ("A" & cell.Row - 1)
'---- DELETE THE ENTIRE ROW
wsPreviousYear.Rows(cell.Row).Delete

Range(ReturnPreviousRow).Select
End If
Next Cell

Please help.
Dec 1 '06 #4
Killer42
8,435 Expert 8TB
Hi.

I apologise as I'm in a rush, and once again don't have time to look into your problem in detail. However, the "every second row" thing probably means you are deleting a row, then moving down to the "next" one. Keep in mind that deleting a row will be moving everything up, so the "next" row is now at the spot you just processed. In this case you need to effectively jump "up" a row, or at least somehow skip the move down.
Dec 3 '06 #5
Killer42
8,435 Expert 8TB
Sorry again, I did find a minute to read further, and I see you've tried to deal with the lost row. I'm not that familiar with addressing of rows, cells etc in Excel, but I would suspect that the ReturnPreviousRow construction might be failing to do what you hope. For one thing, it'll depend on what "previous" means. If it means the row you were just in, that doesn't exist any more.
Dec 3 '06 #6
Yep. That's the problem.

Once a row gets deleted, the next row down becomes the current row, so when the code deletes a row, the next row becomes the current row, but the code may think it has already deleted that row, so it moves on, thus skipping that row that used to be the next row. After I delete a row, it needs to check the same row again in case the next row down has moved up and has become the current row, but I don't know how to get it to do this. As you can see, I tried moving back a row first and then forward again, but that did not work.

Any ideas?
Dec 4 '06 #7
Killer42
8,435 Expert 8TB
Yep. That's the problem.

Once a row gets deleted, the next row down becomes the current row, so when the code deletes a row, the next row becomes the current row, but the code may think it has already deleted that row, so it moves on, thus skipping that row that used to be the next row. After I delete a row, it needs to check the same row again in case the next row down has moved up and has become the current row, but I don't know how to get it to do this. As you can see, I tried moving back a row first and then forward again, but that did not work.
Sorry, in a real rush here again, but could you try just moving back a row and continuing? In other words, does it matter if you process a row twice? Maybe you could even jump back and start from the beginning each time. Inefficient perhaps, but hey, if it works...
Dec 4 '06 #8
Finally got it.

Here's the code for anyone want to do the same thing.

Sub CompareWorksheets()
Dim wbCurrentYear As Workbook, wbPreviousYear As Workbook
Dim wsCurrentYear As Worksheet, wsPreviousYear As Worksheet
Dim rngCurrent As Range, rngPrevious As Range, rngDelete As Range
Dim res As Variant, cell As Range, c, firstAddress
Dim wsCurrentYearLastRow As Long, wsPreviousYearLastRow As Long
Dim wsPreviousYearNextRow As Long

Set wbCurrentYear = Workbooks("New")
Set wbPreviousYear = Workbooks("Old")
Set wsCurrentYear = Worksheets("CurrentYear")
Set wsPreviousYear = Worksheets("PreviousYear")

'---- Current Year Worksheet
With wsCurrentYear
wsCurrentYearLastRow = .Cells(Rows.Count, 1).End(xlUp).Row
Set rngCurrent = .Range("a2:a" & wsCurrentYearLastRow)
End With

'---- Previous Year Worksheet
With wsPreviousYear
wsPreviousYearLastRow = .Cells(Rows.Count, 1).End(xlUp).Row
Set rngPrevious = .Range("a8:a" & wsPreviousYearLastRow)
Set rngDelete = .Range("q8:q" & wsPreviousYearLastRow)
End With


'---- Compare Current Year Worksheet with Previous Year Worksheet
'---- If SSN exists in Current Year Worksheet & Not in Previous Year -
'---- Copy this Row from Current Year Worksheet & Paste into Previous Year Worksheet
wsPreviousYearNextRow = wsPreviousYearLastRow + 1
For Each cell In rngCurrent
res = Application.Match(cell, rngPrevious, 0)
If IsError(res) Then ' Add to end of Previous Year
wsPreviousYear.Cells(wsPreviousYearNextRow, "A") = cell.Value
' wsPreviousYear.Cells(wsPreviousYearNextRow, "R") = "Added"
wsPreviousYearNextRow = wsPreviousYearNextRow + 1
End If
Next cell


'---- Compare Previous Year Worksheet with Current Year Worksheet
'---- If SSN exists in Previous Year Worksheet & Not in Current Year Worksheet -
'---- Delete this Row out of Previous Year Worksheet
For x = rngPrevious.Count To 1 Step -1
Set cell = rngPrevious(x)
res = Application.Match(cell, rngCurrent, 0)
If IsError(res) Then
'---- IF PERSON EXISTS IN PREVIOUS YEAR AND NOT IN CURRENT YEAR,
'---- DELETE THE ENTIRE ROW
wsPreviousYear.Rows(cell.Row).Delete
End If
Next x

End Sub
Dec 5 '06 #9
Killer42
8,435 Expert 8TB
I'm just re-posting Shelley's message with [c o d e] tags for readability, for future reference. It maintains your indenting, and so on.

Glad to hear you got it working, Shelley. :)

Finally got it.

Here's the code for anyone want to do the same thing.
Expand|Select|Wrap|Line Numbers
  1. Sub CompareWorksheets()
  2. Dim wbCurrentYear As Workbook, wbPreviousYear As Workbook
  3. Dim wsCurrentYear As Worksheet, wsPreviousYear As Worksheet
  4. Dim rngCurrent As Range, rngPrevious As Range, rngDelete As Range
  5. Dim res As Variant, cell As Range, c, firstAddress
  6. Dim wsCurrentYearLastRow As Long, wsPreviousYearLastRow As Long
  7. Dim wsPreviousYearNextRow As Long
  8.  
  9. Set wbCurrentYear = Workbooks("New")
  10. Set wbPreviousYear = Workbooks("Old")
  11. Set wsCurrentYear = Worksheets("CurrentYear")
  12. Set wsPreviousYear = Worksheets("PreviousYear")
  13.  
  14. '---- Current Year Worksheet
  15. With wsCurrentYear
  16.     wsCurrentYearLastRow = .Cells(Rows.Count, 1).End(xlUp).Row
  17.     Set rngCurrent = .Range("a2:a" & wsCurrentYearLastRow)
  18. End With
  19.  
  20. '---- Previous Year Worksheet
  21. With wsPreviousYear
  22.     wsPreviousYearLastRow = .Cells(Rows.Count, 1).End(xlUp).Row
  23.     Set rngPrevious = .Range("a8:a" & wsPreviousYearLastRow)
  24.     Set rngDelete = .Range("q8:q" & wsPreviousYearLastRow)
  25. End With
  26.  
  27.  
  28. '---- Compare Current Year Worksheet with Previous Year Worksheet
  29. '---- If SSN exists in Current Year Worksheet & Not in Previous Year -
  30. '---- Copy this Row from Current Year Worksheet & Paste into Previous Year Worksheet
  31. wsPreviousYearNextRow = wsPreviousYearLastRow + 1
  32. For Each cell In rngCurrent
  33.     res = Application.Match(cell, rngPrevious, 0)
  34.     If IsError(res) Then                 ' Add to end of Previous Year
  35.         wsPreviousYear.Cells(wsPreviousYearNextRow, "A") = cell.Value
  36. '        wsPreviousYear.Cells(wsPreviousYearNextRow, "R") = "Added"
  37.         wsPreviousYearNextRow = wsPreviousYearNextRow + 1
  38.     End If
  39. Next cell
  40.  
  41.  
  42. '---- Compare Previous Year Worksheet with Current Year Worksheet
  43. '---- If SSN exists in Previous Year Worksheet & Not in Current Year Worksheet -
  44. '---- Delete this Row out of Previous Year Worksheet
  45. For x = rngPrevious.Count To 1 Step -1
  46.     Set cell = rngPrevious(x)
  47.     res = Application.Match(cell, rngCurrent, 0)
  48.     If IsError(res) Then
  49.         '---- IF PERSON EXISTS IN PREVIOUS YEAR AND NOT IN CURRENT YEAR,
  50.         '---- DELETE THE ENTIRE ROW
  51.         wsPreviousYear.Rows(cell.Row).Delete
  52.     End If
  53. Next x
  54.  
  55. End Sub
Dec 5 '06 #10
Hello experts,

I have a similar but a different issue.. I need your help.

If SSN in previous year worksheet matches with the SSN in Current Year Worksheet, I want to remove that row in current year worksheet.

I didn't understand these two lines of code:
Set rngPrevious = .Range("a1:a" & wsPreviousYearLastRow)
Set rngDelete = .Range("q8:q" & wsPreviousYearLastRow)

I have 1 column (SSN) in previous year worksheet and 3 columns in current year worksheet. How do I modify the code for my requirement.

I have two worksheets in the same excel document.

I really need this working.. Please help me.

Thanks in Advance.
KK.
Mar 28 '07 #11
I really could use this macro but I could not get it to work.
It stops on wb CurrentYear etc.
I have two wooksheets CurrentYear and PreviousYear
I am confused by workbook "new" and wookbook "old"
I am new to marco so any help would be appricated.
Stephen
May 24 '07 #12
danp129
323 Expert 256MB
I think NEW and OLD is referring to the name of an XLS file that's already open such as BOOK1, BOOK2 etc.
May 24 '07 #13
Thanks danp129,

I have only the current year workbook open with two worksheets CurentYear and PreviousYear.

How can I get the macro to work on this bases.

Appriciate any help,
Stephen
May 26 '07 #14

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

Similar topics

0
by: B | last post by:
Using Access2000, the sample code below is what I have been modifying and working on since the past week and I could not get it to work properly. What I wanted to accomplish: 1) read from a...
2
by: codejockey | last post by:
I have a simple project that requires I take a set of data from an Excel spreadsheet, compare it to a table in SQL Server (where column names match), and if there are changes in the Excel sheet,...
0
by: codejockey | last post by:
Please forgive the repost, but I'm trying to avoid the hack I want to implement since I cant get this sample to work. Can anyone help? *********************** William: Thanks for the reply. I...
2
by: Geoff Jones | last post by:
Hi Can anybody tell me how to get the names of the worksheets in an Excel file without creating an Excel object i.e. Excel itself may not be on the machine using the application which looks at...
1
by: J Daniel Melton | last post by:
Hello, I am using late binding in a managed VC++ .NET 2003 application. I used KB 302902 (for C#) as a starting point and converted it to managed C++. I built a managed class that is intantiated...
4
by: e.h.doxtator | last post by:
All I'm a Python newbie, and I'm just getting to the wonders of COM programming. I am trying to programmatically do the following: 1. Activate Excel 2. Add a Workbook 3. Add a Worksheet...
0
by: kkavitha | last post by:
Hello experts, I have a similar issue that is posted here but little bit different.. I need your help. If SSN in previous year worksheet matches with the SSN in Current Year Worksheet, I want...
2
by: cbs81 | last post by:
hi all, problem: transferring data from workbooks that are stored in a particular directory from excel to a table in access. when done, the workbooks that have been processed are automatically...
2
by: harichinna | last post by:
Hi to all, My name is hari, iam trying to delete the column value of spread sheet using c sharp, iam trying to get the value and compare, when comparing it showing some errors, can any one help...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.