Solved

Copy rows from one workbook to another with criteria

Posted on 2015-02-19
6
95 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
6 Comments
 
LVL 23

Expert Comment

by:Michael74
ID: 40620241
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
ID: 40620430
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
ID: 40620434
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
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 

Author Comment

by:swjtx99
ID: 40620440
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
ID: 40620456
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
ID: 40621022
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Freeze panes is an option within all variants of Excel to enable parts of a sheet to remain stationary when the cursor is in another part of the sheet. This is a very useful feature which is overlooked or under used.
When you see single cell contains number and text, and you have to get any date out of it seems like cracking our heads.
The viewer will learn how to create a normally distributed random variable in Excel, use a normal distribution to simulate the return on an investment over a period of years, Create a Monte Carlo simulation using a normal random variable, and calcul…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

726 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