-1

I also need to change the "destination" of the merged data to be pasted starting on cell row 4.The code I found in Microsoft.com (with a little modification thanks to the answer below) is as follow

Sub Button1_Click()
    Dim MyPath As String, FilesInPath As String
    Dim MyFiles() As String
    Dim SourceRcount As Long, FNum As Long
    Dim mybook As Workbook, BaseWks As Worksheet
    Dim sourceRange As Range, destrange As Range
    Dim rnum As Long, CalcMode As Long

   ' Change this to the path\folder location of your files.
   MyPath = "C:\Documents and Settings\laragon2\Desktop\Week's Routers"

   ' Add a slash at the end of the path if needed.
   If Right(MyPath, 1) <> "\" Then
        MyPath = MyPath & "\"
   End If

   ' If there are no Excel files in the folder, exit.
   FilesInPath = Dir(MyPath & "*.xl*")
   If FilesInPath = "" Then
       MsgBox "No files found"
       Exit Sub
   End If

   ' Fill the myFiles array with the list of Excel files
   ' in the search folder.
   FNum = 0
   Do While FilesInPath <> ""
       FNum = FNum + 1
       ReDim Preserve MyFiles(1 To FNum)
       MyFiles(FNum) = FilesInPath
       FilesInPath = Dir()
   Loop

   ' Set various application properties.
   With Application
       CalcMode = .Calculation
       .Calculation = xlCalculationManual
       .ScreenUpdating = False
       .EnableEvents = False
   End With

   ' Add a new workbook with one sheet.
   Set BaseWks = ThisWorkbook.Sheets("Routers")
   rnum = 1

   ' Loop through all files in the myFiles array.
   If FNum > 0 Then
       For FNum = LBound(MyFiles) To UBound(MyFiles)
           Set mybook = Nothing
           On Error Resume Next
           Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
           On Error GoTo 0

           If Not mybook Is Nothing Then
               On Error Resume Next

               ' Change this range to fit your own needs.
               With mybook.Worksheets(1)
                   Set sourceRange = .Range("A4", .Range("E700").End(xlUp))
               End With

               If Err.Number > 0 Then
                   Err.Clear
                   Set sourceRange = Nothing
               Else
                   ' If source range uses all columns then
                   ' skip this file.
                   If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                       Set sourceRange = Nothing
                   End If
               End If
               On Error GoTo 0

               If Not sourceRange Is Nothing Then
                   SourceRcount = sourceRange.Rows.Count

                   If rnum + SourceRcount >= BaseWks.Rows.Count Then
                       MsgBox "There are not enough rows in the target worksheet."
                       BaseWks.Columns.AutoFit
                       mybook.Close savechanges:=False
                       GoTo ExitTheSub
                   Else
                       ' Copy the file name in column A.
                       With sourceRange
                           BaseWks.Cells(rnum, "A"). _
                                    Resize(.Rows.Count).Value = MyFiles(FNum)
                       End With

                       ' Set the destination range.
                       Set destrange = BaseWks.Range("b4")

                       ' Copy the values from the source range
                       ' to the destination range.
                       With sourceRange
                           Set destrange = destrange. _
                                        Resize(.Rows.Count, .Columns.Count)
                       End With
                       destrange.Value = sourceRange.Value

                       rnum = rnum + SourceRcount
                   End If
               End If
               mybook.Close savechanges:=False
           End If

       Next FNum
       BaseWks.Columns.AutoFit
   End If

ExitTheSub:
  ' Restore the application properties.
   With Application
       .ScreenUpdating = True
       .EnableEvents = True
       .Calculation = CalcMode
   End With
End Sub
CuberChase
  • 4,458
  • 5
  • 33
  • 52
user2030857
  • 9
  • 2
  • 6
  • what is the question, where are you stuck? Please read the FAQ with instructions http://stackoverflow.com/questions/how-to-ask and a personal favorite of mine: http://mattgemmell.com/2008/12/08/what-have-you-tried – K_B Apr 29 '13 at 17:52
  • I don't know how to change the range of cells being copied ( i want it to select from A2 to the last active cell) and i also need to change the "destination" of the merged data to cell A4 – user2030857 Apr 29 '13 at 18:04
  • When you say last active cell, do you mean the last cell which has data? If yes then my next question is are you looking for the last cell in the same column or in the worksheet? – Siddharth Rout Apr 29 '13 at 18:35
  • YES, the last cell with data, and all the columns in the worksheet. Also, the merged data i need it copied into A4. – user2030857 Apr 29 '13 at 18:44
  • 1
    To find the last cell in a column/worksheet see [THIS](http://stackoverflow.com/questions/11169445/error-finding-last-used-cell-in-vba) – Siddharth Rout Apr 29 '13 at 18:55

1 Answers1

0

The source range is being set in the line immediately after: ' Change this range to fit your own needs. It looks like this:

Set sourceRange = .Range("A1:C1")

The destination is being set in the line immediately after the comment indicating: ' Set the destination range. It looks like this:

Set destrange = BaseWks.Range("B" & rnum)

EDIT Here is an example. Create an empty workbook. Put some values in cells A1:A5 on sheet 1. The do this:

Sub CopyRangeToRange()
    Dim sourceRange As Range
    Dim destRange As Range

    Set sourceRange = Range("A1:A5")

    Set destRange = Sheets(2).Range("A1")

    With sourceRange
        Set destRange = destRange.Resize( _
            .Rows.Count, .Columns.Count)
    End With

    Sheets(2).Activate
    destRange.Activate
    destRange.Value = sourceRange.Value

End Sub

This is the exact same method I propose above. If this works, but the macro you are writing does not work, you need to debug where it is going wrong, because the method is the same.

EDIT #2

After trying this on your workbook, I think this is what you're after. I believe I commented all of my changes, which you can find by the '## comments. Almost all of the changes applied within the With sourcerange block. I also changed the initial value of rnum to 4, since that seems to be where the data should begin being pasted in the Routers worksheet, and modified the way rnum increments for each file in the loop.

Sub Button1_Click()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String
Dim SourceRcount As Long, FNum As Long, mybook As Workbook
Dim BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long

' Change this to the path\folder location of your files.
MyPath = "C:\Documents and Settings\laragon2\Desktop\Week's Routers"

' Add a slash at the end of the path if needed.
If Right(MyPath, 1) <> "\" Then
    MyPath = MyPath & "\"
End If

' If there are no Excel files in the folder, exit.
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
    MsgBox "No files found"
    Exit Sub
End If

' Fill the myFiles array with the list of Excel files
' in the search folder.
FNum = 0
Do While FilesInPath <> ""
    FNum = FNum + 1
    ReDim Preserve MyFiles(1 To FNum)
    MyFiles(FNum) = FilesInPath
    FilesInPath = Dir()
Loop

' Set various application properties.
With Application
    CalcMode = .Calculation
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
    .EnableEvents = False
End With

' Set the destination worksheet:'
Set BaseWks = ThisWorkbook.Sheets("Routers")

'## set rnum to 4 because we begin pasting data in row 4... ##'
rnum = 4

' Loop through all files in the myFiles array.
If FNum > 0 Then
    For FNum = LBound(MyFiles) To UBound(MyFiles)
        Set mybook = Nothing
        On Error Resume Next
        Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
        On Error GoTo 0

        If Not mybook Is Nothing Then
            On Error Resume Next

            ' Change this range to fit your own needs.
            With mybook.Worksheets(1)
                Set sourceRange = .Range("A4", .Range("E4:E700").End(xlUp))  '## changed dz ##'
            End With

            If Err.Number > 0 Then
                Err.Clear
                Set sourceRange = Nothing
            Else
                ' If source range uses all columns then
                ' skip this file.
                If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                    Set sourceRange = Nothing
                End If
            End If
            On Error GoTo 0

            If Not sourceRange Is Nothing Then

                SourceRcount = sourceRange.Rows.Count

                If rnum + SourceRcount >= BaseWks.Rows.Count Then
                    MsgBox "There are not enough rows in the target worksheet."
                    BaseWks.Columns.AutoFit
                    mybook.Close savechanges:=False
                    GoTo ExitTheSub
                Else

                    ' Copy the file name in column A.
                    BaseWks.Activate
                    With sourceRange
                    ''## changed to make this range the same number of rows as sourceRange ##'
                        BaseWks.Cells(rnum, 1). _
                                Resize(.Rows.Count).Value = MyFiles(FNum)
                    '## moved this code and changed to begin at the last non-blank row in column A, but use column B ##'
                    '## resize the destrange to the same dimensions as sourcerange ##'
                        Set destrange = BaseWks.Cells(rnum, 1). _
                                Resize(.Rows.Count, .Columns.Count).Offset(, 1)
                    '## Insert the source values in the destination range ##'
                        destRange.Value = .Value
                    '## increment rnum to the next appropriate value ##'
                        rnum = rnum + .Rows.Count
                    End With

                    '## Removed as redundant
                    'With sourceRange
                    '    Set destrange = destrange. _
                    '                    Resize(.Rows.Count, .Columns.Count)
                    'End With

                    ' Copy the values from the source range
                    ' to the destination range.
                    '## This has been moved to above. ##
                    ' destrange.Value = sourceRange.Value


                End If
            End If
            mybook.Close savechanges:=False
        End If

    Next FNum
    BaseWks.Columns.AutoFit
End If
ExitTheSub:
' Restore the application properties.
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With
End Sub
David Zemens
  • 53,033
  • 11
  • 81
  • 130
  • how can i make it so the source is A2 to the last cell with data?, I dont think im sure of what to do. – user2030857 Apr 30 '13 at 12:50
  • For Excel 2007+, `=.Range("A2", .Range("A1048576").End(xlUp))`. For Excel 2003: `=.Range("A2", .Range("A65536").End(xlUp))` – David Zemens Apr 30 '13 at 13:44
  • The first part worked, but the second part is not moving the paste to start in row 4, I tried putting Set destrange = BaseWks.Range("B4" & rnum), and it doesnt do a thing. – user2030857 Apr 30 '13 at 14:37
  • the expression `"B4" & rnum` will not put it in row 4 unless `rnum = 0. Try getting rid of `& rnum` if you always want to paste to row 4. – David Zemens Apr 30 '13 at 14:45
  • It not working, i used Set destrange = BaseWks.Range("b" & rnum) rnum=4, i deleted the & rnum, but nothing seems to be working – user2030857 Apr 30 '13 at 15:12
  • Are you getting an error? If you're not getting an error, it *is* working, it's just not doing what you expect it to do. Please upload a copy of your file, or describe in more detail the error message, if any. – David Zemens Apr 30 '13 at 15:21
  • I cannot put any images to show you what is happening. I did updated the question to reflect the missing part( pasting into row 4) – user2030857 Apr 30 '13 at 16:52
  • well if you can't show me what's happening, I can't possibly be of any further assistance. You could upload the file to Google Docs, Dropbox, etc., or upload images to imgur.com... – David Zemens Apr 30 '13 at 17:45
  • that's not at all helpful. What is the error? Is there an error? – David Zemens Apr 30 '13 at 17:55
  • You do realize this is pasting the data on to another worksheet, right? Are you sure you're looking at the destination worksheet defined by `BaseWks` variable? – David Zemens Apr 30 '13 at 17:57
  • Right now it is pasting in the the sheet i need it, but i just want to move it 4 rows down. I just dont know how to do it. – user2030857 Apr 30 '13 at 18:01
  • It doesnt give me an error per say, it just doesnt paste the data starting on row 4 – user2030857 Apr 30 '13 at 18:02
  • Where *does* it put the data? If you're not getting an error, it's definitely putting the data *somewhere*. Try adding this line `destrange.Activate` right before the line that pastes the values: `destrange.Value = sourceRange.Value`. Put a breakpoint on that line, and step through it using F8 in the debugger. What happens when you `destRange.Activate`? – David Zemens Apr 30 '13 at 18:14
  • it gives me a runtime error "1004" http://imgur.com/PyZUNvn , did i do it in the right order? – user2030857 Apr 30 '13 at 18:27
  • OK. That's on another sheet... do `BaseWks.Activate` and then `destRange.Activate` – David Zemens Apr 30 '13 at 18:35
  • Nothing changed. the only difference is no errors this time. http://imgur.com/UvNQZj2 – user2030857 Apr 30 '13 at 18:47
  • Something happens. Please tell me what happens when you step through this using the debugger. Does the worksheet get activated? Does `destRange` get selected/activated? – David Zemens Apr 30 '13 at 19:19
  • Please check the file and let me know what you can do, now the importing is not pulling all the data, i need it so every working in the folder is merged into the document to follow, starting in row 4 and the destination also in row 4 https://docs.google.com/file/d/0B8_IB8QXrzbEbDNFZGpkZXB3R3c/edit?usp=sharing – user2030857 May 01 '13 at 13:42
  • You're constantly overwriting the data -- with each iteration of the loop you're going back to B4 and pasting the values back over what was done in the previous iteration. I can fix this probably, but I am in meetings all day and will not have time to look at it until this evening. – David Zemens May 01 '13 at 13:54
  • Thank you for taking your time with this mess. I wish i had more knowledge with VBA to figure this out. The data is now being copied properly ( nothing is missing) but it is still being pasted at the beginning of the sheet. Your help is greatly appreciated. – user2030857 May 01 '13 at 13:59
  • OK I have done pretty much everything I can think of. Seems to be working at least as far as I expect it to work. begins by putting data in rows 4 (for as many rows identified in `sourcerange`) and then finds the next empty row and continues for the next file/next `sourcerange`. – David Zemens May 02 '13 at 02:32
  • I had to change the Set sourceRange = .Range("A4", .Range("E700").End(xlUp)) since it was not copying all the data. You are awesome!!!. thank you so much for your help and persistence. i will invite you drink whenever you come and visit Miami, F – user2030857 May 02 '13 at 13:16