473,626 Members | 3,239 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

4 New Member
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 CompareWorkshee ts()
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("Cur rentYear")
Set wsPreviousYear = Worksheets("Pre viousYear")

'---- Current Year Worksheet
With wsCurrentYear
wsCurrentYearLa stRow = .Cells(Rows.Cou nt, 1).End(xlUp).Ro w
Set rngCurrent = .Range("a2:a" & wsCurrentYearLa stRow)
End With

'---- Previous Year Worksheet
With wsPreviousYear
wsPreviousYearL astRow = .Cells(Rows.Cou nt, 1).End(xlUp).Ro w
Set rngPrevious = .Range("a8:a" & wsPreviousYearL astRow)
Set rngDelete = .Range("q8:q" & wsPreviousYearL astRow)
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
wsPreviousYearN extRow = wsPreviousYearL astRow + 1
For Each cell In rngCurrent
res = Application.Mat ch(cell, rngPrevious, 0)
If IsError(res) Then ' Add to end of Previous Year
wsPreviousYear. Cells(wsPreviou sYearNextRow, "A") = cell.Value
wsPreviousYear. Cells(wsPreviou sYearNextRow, "R") = "Added"
wsPreviousYearN extRow = wsPreviousYearN extRow + 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.Mat ch(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:=xlValue s)
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 6950
Killer42
8,435 Recognized Expert Expert
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 Recognized Expert Expert
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
Shelley
4 New Member
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.Mat ch(cell, rngCurrent, 0)
If IsError(res) Then
Dim ReturnPreviousR ow
ReturnPreviousR ow = ("A" & cell.Row - 1)
'---- DELETE THE ENTIRE ROW
wsPreviousYear. Rows(cell.Row). Delete

Range(ReturnPre viousRow).Selec t
End If
Next Cell

Please help.
Dec 1 '06 #4
Killer42
8,435 Recognized Expert Expert
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 Recognized Expert Expert
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 ReturnPreviousR ow 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
Shelley
4 New Member
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 Recognized Expert Expert
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
Shelley
4 New Member
Finally got it.

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

Sub CompareWorkshee ts()
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 wsCurrentYearLa stRow As Long, wsPreviousYearL astRow As Long
Dim wsPreviousYearN extRow As Long

Set wbCurrentYear = Workbooks("New" )
Set wbPreviousYear = Workbooks("Old" )
Set wsCurrentYear = Worksheets("Cur rentYear")
Set wsPreviousYear = Worksheets("Pre viousYear")

'---- Current Year Worksheet
With wsCurrentYear
wsCurrentYearLa stRow = .Cells(Rows.Cou nt, 1).End(xlUp).Ro w
Set rngCurrent = .Range("a2:a" & wsCurrentYearLa stRow)
End With

'---- Previous Year Worksheet
With wsPreviousYear
wsPreviousYearL astRow = .Cells(Rows.Cou nt, 1).End(xlUp).Ro w
Set rngPrevious = .Range("a8:a" & wsPreviousYearL astRow)
Set rngDelete = .Range("q8:q" & wsPreviousYearL astRow)
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
wsPreviousYearN extRow = wsPreviousYearL astRow + 1
For Each cell In rngCurrent
res = Application.Mat ch(cell, rngPrevious, 0)
If IsError(res) Then ' Add to end of Previous Year
wsPreviousYear. Cells(wsPreviou sYearNextRow, "A") = cell.Value
' wsPreviousYear. Cells(wsPreviou sYearNextRow, "R") = "Added"
wsPreviousYearN extRow = wsPreviousYearN extRow + 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.Cou nt To 1 Step -1
Set cell = rngPrevious(x)
res = Application.Mat ch(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 Recognized Expert Expert
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

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

Similar topics

0
2067
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 recordset and export to Excel 2) Excel is populated based from an ID (may possible be one or multiple) and renames the worksheet based from the ID 3) the code also format the fields The sample database may be downloaded at:
2
9938
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, update the SQL Server table with said changes. The datasets are about 2000 rows. My thinking is performing a check row by row is inefficient, so I thought about how I could compare the two as datasets and resolve differences. The SQL Server table...
0
1575
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 havent been able to get the sample to work. I notice the cursor cycling through the Excel records, but the SQL table always shows up empty. Notice anything wrong here?
2
1243
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 the Excel files. Thanks in advance Geoff
1
3648
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 by a form. The class can instantiate Excel, open a new workbook, add a new worksheet, get a range, and put some data in it. So, I have basically just duplicated what KB 302902 does, except I am working out of a managed C++ class. The problem...
4
14545
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 4. Populate the new Worksheet 5. Repeat steps 3,4 while there is data.
0
1057
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 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)
2
1835
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 moved into a directory named “processed” . all using vba. this is the pretty complex vb problem that i need some expert solution to. overview. i have created a cash reconciliation application in excel saved by month for each of my bus...
2
2527
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 me, to slove this issue i pasted code below Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook ObjWorkBook=null; ...
0
8269
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
8203
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8368
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
8512
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4094
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
4206
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2630
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
1
1815
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1515
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.