简体   繁体   中英

Copying Consolidating Data from Multiple Worksheets into .ActiveWorksheet

I've been working from this article to try and consolidate data from multiple worksheets into a single summary worksheet. I've nearly got it working but I'm struggling to alter the destination worksheet.

I'm trying to have the consolidated data appear into cell B4 on the Consolidated Tracker sheet.

 With CopyRng

         Set DestSh = ThisWorkbook.Worksheets("Consolidated Tracker")
         Set myRange = DestSh.Range("B4")

 End With

Problem is myRange is always empty and nothing is copied over.

No error, seems to execute f8 as expected without copying anything over.


Full Code for reference:

Sub CopyRangeFromMultiWorksheets()

    Dim sh As Worksheet
    Dim DestSh As Worksheet
    Dim Last As Long
    Dim CopyRng As Range

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    ' Loop through all worksheets and copy the data to the
    ' summary worksheet.
    For Each sh In ActiveWorkbook.Worksheets

            ' Find the last row with data on the summary worksheet.
            Last = LastRow(DestSh)

            ' Specify the range to place the data.
            Set CopyRng = sh.Range("B4:B50")

            ' This statement copies values
            With CopyRng
                 Set DestSh = ThisWorkbook.Worksheets("Consolidated Tracker")
                 Set myRange = DestSh.Range("B4")
            End With

        'End If
    Next

ExitTheSub:

    Application.Goto DestSh.Cells(4, 2)

    ' AutoFit the column width in the summary sheet.
    DestSh.Columns.AutoFit

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
End Sub    

The issue is that the code never actually execute any type of command to move the data. The code only sets variables.

Look at the modified code below, specifically the last line before the End With.

' Specify the range to place the data.
Set CopyRng = sh.Range("B4:B50")

' This statement copies values
With CopyRng
    Set DestSh = ThisWorkbook.Worksheets("Consolidated Tracker")
    DestSh.Range("B4").Resize(CopyRng.Rows.Count,1).Value = CopyRng.Value
End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM