Solved

Loop Copy data from different  Workbook

Posted on 2011-03-15
12
201 Views
Last Modified: 2012-05-11
Hi Experts,

I would like to request Experts help to copy data (only number) from Column A for all sheets at Workbook1 and paste it at “CopyData” Workbook at “Data” sheet at Column A. I need to loop this function so that I can copy other workbooks which is also having the similar data format (currently I’m having 14 workbook). Different workbook data need to copy  at  different  Column at “CopyData” workbook. Hope Experts will help me to create this macro.



CopyData.xls
Workbook1.xls
0
Comment
Question by:Cartillo
  • 7
  • 5
12 Comments
 
LVL 18

Expert Comment

by:Curt Lindstrom
ID: 35147379
Try these 2 macros. The assume the data to be copied starts at row 8 on each sheet in your workbooks that you copy from. Try the code in the attached file. You need to provide the correct filename and path for your workbook(s)

Curt
Sub Copy_Data()
    Dim Ws As Worksheet
    Dim Wb As Workbook
    Dim i As Long, j As Long, k As Long, Col As Long
    Dim SourceFile As String
    Dim FlPath As String

    FlPath = "c:/Mydata/" 'Change to the path where you store your workbooks to be copied
    For Col = 1 To 1    'Change the last 1 to the number filenames you got entered on row 1 and stored in your file path
        FlName = ThisWorkbook.Worksheets("Data").Cells(1, Col)
        SourceFile = FlPath & FlName

        Workbooks.Open Filename:=SourceFile
        Set Wb = ActiveWorkbook
        k = 2
        For Each Ws In Wb.Worksheets
            With Ws
                For j = 8 To xlLastRow(Ws.Name)
                    i = j + k - 8
                    If .Cells(j, 1).Value = "" Then
                        k = k - 1
                    Else
                        ThisWorkbook.Worksheets("Data").Cells(i, 1) = .Cells(j, 1)
                    End If
                Next j
            End With
            k = i + 1
        Next Ws
    Next Col
    ThisWorkbook.Activate
    Range("A1").Select
End Sub
Function xlLastRow(Optional WorksheetName As String) As Long
     
    'Check for optional worksheetname else use activesheet
    If WorksheetName = vbNullString Then
        WorksheetName = ActiveSheet.Name
    End If
    
     '    find the last populated row in a worksheet
    With Worksheets(WorksheetName)
        xlLastRow = .Cells.Find("*", .Cells(1), xlFormulas, _
        xlWhole, xlByRows, xlPrevious).Row
    End With
     
End Function

Open in new window

CopyData.xls
0
 

Author Comment

by:Cartillo
ID: 35148903
Hi Curt,

Can I select the workbook instead of naming it. I have various workbook name. Also each workbook need to copied at different column. Hope you add this feature.  
0
 
LVL 18

Expert Comment

by:Curt Lindstrom
ID: 35152199
You can select the workbooks if you want to do that.

Just to clarify what the idea with the current code is:

1. You have all your workbooks in the same folder
2. You replace the names on row 1 in the CopyData file with the real names.
3. You change line 8 in the code and enter your own path
4. You change line 9 in the code to how many workbooks you are processing

You press the button and all the workbooks are processed and copied to the correct columns.

Before I attempt to update the macro:

1. Do you want to select all the workbooks in one go? For that to work they need to be in their own unique folder.
2. Or do you want to select the workbooks one by one from different folders?

Curt
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 

Author Comment

by:Cartillo
ID: 35152883
Hi Curt,

> Do you want to select all the workbooks in one go? For that to work they need to be in their own unique folder.

- I'll select the workbooks one by one from different folders
0
 
LVL 18

Expert Comment

by:Curt Lindstrom
ID: 35153104
Try this code. It's included in the attached file where you can try it.

Cheers,
Curt
Sub Copy_Data()
    Dim Ws As Worksheet
    Dim Wb As Workbook
    Dim i As Long, j As Long, k As Long, Col As Long
    Dim SourceFile As String, Response As String

    Col = 1
    Do Until LCase(Left(Response, 1)) = "n"
        SourceFile = Application.GetOpenFilename(Title:="Please select your file from the folder that contains the data, then click Open.")
        If SourceFile = "False" Then
            MsgBox ("No file selected!")
            Exit Sub
        End If


        Workbooks.Open SourceFile
        Set Wb = ActiveWorkbook
        k = 2
        For Each Ws In Wb.Worksheets
            With Ws
                For j = 8 To xlLastRow(Ws.Name)
                    i = j + k - 8
                    If .Cells(j, 1).Value = "" Then
                        k = k - 1
                    Else
                        ThisWorkbook.Worksheets("Data").Cells(i, Col) = .Cells(j, 1)
                    End If
                Next j
            End With
            k = i + 1
        Next Ws
        Wb.Close
        Response = InputBox("Process another workbook?", , "Yes")
        Col = Col + 1
    Loop
    ThisWorkbook.Activate
    Range("A1").Select
End Sub
Function xlLastRow(Optional WorksheetName As String) As Long
     
    'Check for optional worksheetname else use activesheet
    If WorksheetName = vbNullString Then
        WorksheetName = ActiveSheet.Name
    End If
    
     '    find the last populated row in a worksheet
    With Worksheets(WorksheetName)
        xlLastRow = .Cells.Find("*", .Cells(1), xlFormulas, _
        xlWhole, xlByRows, xlPrevious).Row
    End With
     
End Function

Open in new window

CopyData-2.xls
0
 

Author Comment

by:Cartillo
ID: 35157877
Hi,

Few workbook facing problem whilst copying the data, shows error as "Object variable or with block variable not set at this line:  


 xlLastRow = .Cells.Find("*", .Cells(1), xlFormulas, _
        xlWhole, xlByRows, xlPrevious).Row

How to fix this?
0
 
LVL 18

Expert Comment

by:Curt Lindstrom
ID: 35161325
Let's get rid of the Function. Try this one. If you still have problems maybe you can post a sample of a failing workbook.
The code is include in the attached file.

Curt
Sub Copy_Data()
    Dim Ws As Worksheet
    Dim Wb As Workbook
    Dim i As Long, j As Long, k As Long, Col As Long, xlLastRow As Long
    Dim SourceFile As String, Response As String

    Col = 1
    Do Until LCase(Left(Response, 1)) = "n"
        SourceFile = Application.GetOpenFilename(Title:="Please select your file from the folder that contains the data, then click Open.")
        If SourceFile = "False" Then
            MsgBox ("No file selected!")
            Exit Sub
        End If


        Workbooks.Open SourceFile
        Set Wb = ActiveWorkbook
        k = 2
        For Each Ws In Wb.Worksheets
        xlLastRow = Range("A65536").End(xlUp).Row
            With Ws
                For j = 8 To xlLastRow
                    i = j + k - 8
                    If .Cells(j, 1).Value = "" Then
                        k = k - 1
                    Else
                        ThisWorkbook.Worksheets("Data").Cells(i, Col) = .Cells(j, 1)
                    End If
                Next j
            End With
            k = i + 1
        Next Ws
        Wb.Close
        Response = InputBox("Process another workbook?", , "Yes")
        Col = Col + 1
    Loop
    ThisWorkbook.Activate
    Range("A1").Select
End Sub

Open in new window

CopyData-3.xls
0
 
LVL 18

Accepted Solution

by:
Curt Lindstrom earned 500 total points
ID: 35161395
Sorry, a small error with the new line. Change Line 20 in the code to:

        xlLastRow = Ws.Range("A65536").End(xlUp).Row

Fixed in attached file

Curt

CopyData-3.xls
0
 
LVL 18

Expert Comment

by:Curt Lindstrom
ID: 35177580
Hi Cartillo,

Any more problems with this or is everything working ok now?

Curt
0
 

Author Comment

by:Cartillo
ID: 35177760
Hi Curt,

It works perfectly. Thanks for the great help.
0
 

Author Closing Comment

by:Cartillo
ID: 35177764
Hi Curt,

Thanks for the help.
0
 
LVL 18

Expert Comment

by:Curt Lindstrom
ID: 35177782
Great! Glad to help!

Cheers,
Curt
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering 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

Excel can be a tricky bit of software to get your head around. Whilst you’ll be able to eventually get to grips with the basic understanding of how to get by, there are a few Excel tips that not everybody will even know about let alone know how to d…
Do you use a spreadsheet like Microsoft's Excel?  Have you ever wanted to link out to a non excel file on your computer or network drive?  This is the way I found to do it!
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…
This Micro Tutorial will demonstrate how to create pivot charts out of a data set. I also added a drop-down menu which allows to choose from different categories in the data set and the chart will automatically update.

861 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