Solved

Copy rows from one workbook to another with criteria

Posted on 2015-02-19
6
87 Views
Last Modified: 2015-02-20
Hi,

I am trying to adapt some code from an Expert to another problem.

I have two workbooks, Both have dates in column A. I want to open the source pull all rows from the source workbook who's date in column A is greater than the latest date in Column A of the destination workbook (could be any name). The macro runs in the destination workbook. The following runs without errors but doesn't pull any rows over.

Option Explicit


Sub LoadData()
    Dim LastRow As Long
    Dim MainFile As String
    Dim SrcFile As String
    Dim WS1 As Worksheet
    Dim WS2 As Worksheet
    Dim cCell As Range
    Dim MaxDate As Date
    Dim I As Long, MaxRow1 As Long, MaxRow2 As Long
   
   ' Application.ScreenUpdating = False
    MainFile = ActiveWorkbook.Name 'name of the workbook with the macro which is the destination workbook
    Workbooks.Open "c:\!data/testdata.xls" '<do I need to activate this workbook before proceeding?
    SrcFile = ActiveWorkbook.Name 'name of the source workbook
    Workbooks(SrcFile).Worksheets("Sheet1").Select
   
Dim rng1 As Range ' fixes dates on source workbook
Dim X
Set rng1 = Range([A1], Cells(Rows.Count, "A").End(xlUp))
X = rng1
rng1 = X

   
Set WS1 = Workbooks(SrcFile).Sheets("Sheet1")
MaxRow1 = WS1.Range("A" & WS1.Rows.Count).End(xlUp).Row
MaxDate = Application.WorksheetFunction.Max(WS1.Range("A:A"))

Set WS2 = Workbooks(MainFile).Sheets("Raw Data")
MaxRow2 = WS2.Range("A" & WS2.Rows.Count).End(xlUp).Row

For I = 2 To MaxRow2
    If WS2.Cells(I, "A") > MaxDate Then
        WS2.Cells(I, "A").EntireRow.Copy WS1.Cells(MaxRow1, "A")
        MaxRow1 = MaxRow1 + 1
    End If
Next I
   
   
    Application.DisplayAlerts = False  'avoids clipboard message
    Workbooks(SrcFile).Close SaveChanges:=False
    Application.DisplayAlerts = True

    Workbooks(MainFile).Worksheets("Table").Select
     
    Application.ScreenUpdating = True
    MsgBox "Data was successfully imported!", vbInformation
End Sub

Hoping someone can see what I'm doing wrong without having to post example workbooks but I could if necessary.

Thanks in advance,

swjtx99
0
Comment
Question by:swjtx99
  • 3
  • 3
6 Comments
 
LVL 23

Expert Comment

by:Michael74
Comment Utility
Try this

Sub LoadData()
    Dim srcWb As Workbook
    Dim srcWs As Worksheet, destWs As Worksheet
    Dim maxDate As Date
    Dim i As Long, destCurrRow
    
   ' Application.ScreenUpdating = False
    DestWb = ActiveWorkbook 'name of the workbook with the macro which is the destination workbook
    Set destWs = ActiveWorkbook.Sheets("Raw Data")
    Set srcWb = Workbooks.Open("c:\!data/testdata.xls")
    Set srcWs = srcWb.Sheets("Sheet1")
    
    'Get Max Date
    maxDate = Application.WorksheetFunction.Max(destWs.Range("A:A"))
    
    destCurrRow = destWs.Range("A" & Rows.Count).End(xlUp).Row + 1

    For i = 2 To srcWs.Range("A" & Row.Count).End(xlUp).Row
        If srcWs.Range("A" & i).Value > maxDate Then
            srcWs.Range("A" & i).EntireRow.Copy destWs.Range("A" & destCurrRow)
            destCurrRow = destCurrRow + 1
        End If
    Next i
    
    Application.DisplayAlerts = False  'avoids clipboard message
    srcWb.Close SaveChanges:=False
    Application.DisplayAlerts = True

    Workbooks(MainFile).Worksheets("Table").Select
      
    Application.ScreenUpdating = True
    MsgBox "Data was successfully imported!", vbInformation
End Sub

Open in new window


Just a note but always try to use meaningful variable names as it makes your code far easier to read
0
 

Author Comment

by:swjtx99
Comment Utility
Hi Michael74,

Thanks for the reply. I'm getting Run Time error 438 "Object doesn't support this property or method on the first line of code after the Dim statements:

DestWb = ActiveWorkbook 'name of the workbook with the macro which is the destination workbook

Any ideas? Should I use "ThisWorkbook"?

Thanks,

swjtx99
0
 
LVL 23

Expert Comment

by:Michael74
Comment Utility
Sorry this line should be

Set DestWb = ActiveWorkbook

Open in new window


ThisWorkBook would also achieve the same thing, I just left out the Set keyword.

After having a second look this line is not required anyway and it is just there because I forgot to clean it up. Here is amended code

Sub LoadData()
    Dim srcWb As Workbook
    Dim srcWs As Worksheet, destWs As Worksheet
    Dim maxDate As Date
    Dim i As Long, destCurrRow As Long
    
    Application.ScreenUpdating = False
    Set destWs = ActiveWorkbook.Sheets("Raw Data")
    Set srcWb = Workbooks.Open("c:\!data/testdata.xls")
    Set srcWs = srcWb.Sheets("Sheet1")
    
    'Get Max Date
    maxDate = Application.WorksheetFunction.Max(destWs.Range("A:A"))
    
    destCurrRow = destWs.Range("A" & Rows.Count).End(xlUp).Row + 1

    For i = 2 To srcWs.Range("A" & Row.Count).End(xlUp).Row
        If srcWs.Range("A" & i).Value > maxDate Then
            srcWs.Range("A" & i).EntireRow.Copy destWs.Range("A" & destCurrRow)
            destCurrRow = destCurrRow + 1
        End If
    Next i
    
    Application.DisplayAlerts = False  'avoids clipboard message
    srcWb.Close SaveChanges:=False
    Application.DisplayAlerts = True

    Worksheets("Table").Select
      
    Application.ScreenUpdating = True
    MsgBox "Data was successfully imported!", vbInformation
End Sub

Open in new window

0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

Author Comment

by:swjtx99
Comment Utility
Hi Michael74,

Thanks. Now I get runtime error 424 "Object required" on this line:

For i = 2 To srcWs.Range("A" & Row.Count).End(xlUp).Row

Thanks,

swjtx99
0
 
LVL 23

Accepted Solution

by:
Michael74 earned 500 total points
Comment Utility
Doh! Ok I have tested it this time

The problem is I left out the s in rows

For i = 2 To srcWs.Range("A" & Rows.Count).End(xlUp).Row

Open in new window


Sub LoadData()
    Dim srcWb As Workbook
    Dim srcWs As Worksheet, destWs As Worksheet
    Dim maxDate As Date
    Dim i As Long, destCurrRow As Long
    
    Application.ScreenUpdating = False
    Set destWs = ActiveWorkbook.Sheets("Raw Data")
    Set srcWb = Workbooks.Open("C:\Users\michael.fowler\Desktop\Book1.xlsx")
    Set srcWs = srcWb.Sheets("Sheet1")
    
    'Get Max Date
    maxDate = Application.WorksheetFunction.Max(destWs.Range("A:A"))
    
    destCurrRow = destWs.Range("A" & Rows.Count).End(xlUp).Row + 1

    For i = 2 To srcWs.Range("A" & Rows.Count).End(xlUp).Row
        If srcWs.Range("A" & i).Value > maxDate Then
            srcWs.Range("A" & i).EntireRow.Copy destWs.Range("A" & destCurrRow)
            destCurrRow = destCurrRow + 1
        End If
    Next i
    
    Application.DisplayAlerts = False  'avoids clipboard message
    srcWb.Close SaveChanges:=False
    Application.DisplayAlerts = True

    Worksheets("Table").Select
      
    Application.ScreenUpdating = True
    MsgBox "Data was successfully imported!", vbInformation
End Sub

Open in new window

0
 

Author Closing Comment

by:swjtx99
Comment Utility
Hi MIchaei74,

Thank you, it works. I really appreciate the help.

This has, however, created another issue I did not foresee... the code is taking more than 17 minutes to run as the source worksheet has more than 50,000 rows and it's copying over 10,000 to 15,000 that are dated later than the latest date in the destination workbook. Any ideas and/or would you mind if I created another question to ask about improving the run speed of this solution?

Thanks again,

swjtx99
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
excel file 5 42
SUM every other column 10 36
Excel split data and output all combinations. 2 14
Gantt chart 2 8
When designing a form there are several BorderStyles to choose from, all of which can be classified as either 'Fixed' or 'Sizable' and I'd guess that 'Fixed Single' or one of the other fixed types is the most popular choice. I assume it's the most p…
This code takes an Excel list of URL’s and adds a header titled “URL List”. It then searches through all URL’s in column “A”, looking for duplicates. When a duplicate is found, it is moved to the top of the list. The duplicate URL’s are then highlig…
The viewer will learn how to use a discrete random variable to simulate the return on an investment over a period of years, create a Monte Carlo simulation using the discrete random variable, and create a graph to represent the possible returns over…
This Micro Tutorial demonstrate the bugs in Microsoft Excel for Mac with Pivot Charts.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now