Search code examples
excelvbacopyruntime-error

Copy method of Range class failed


I'm trying to copy the entire contents of one Sheet (which is user-inputted) to another Sheet (which is hidden, but not protected). When I run it, I get the error: Run-time error '1004': Copy method of Range class failed.

This is my code:

Sub CopyDataToTable()
    Dim sourceSheet As Worksheet
    Dim targetSheet As Worksheet
    Dim lastRow As Long
    Dim lastColumn As Long
    Dim sourceRange As Range
    Dim targetCell As Range

    ' Set the source and target sheets
    Set sourceSheet = ThisWorkbook.Sheets("Report Data")
    Set targetSheet = ThisWorkbook.Sheets("ReportAsTable")

    ' Find the last row and last column with data in the source sheet
    lastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row
    lastColumn = sourceSheet.Cells(1, sourceSheet.Columns.Count).End(xlToLeft).Column

    ' Set the source range excluding the header row
    Set sourceRange = sourceSheet.Range(sourceSheet.Cells(2, 1), sourceSheet.Cells(lastRow, lastColumn))

    ' Set the target cell where you want to paste the data in the target sheet
    Set targetCell = targetSheet.Cells(2, 1)
    
    ' Copy the data from the source range to the target cell
    sourceRange.Copy targetCell
    
    ' Clear the clipboard
    Application.CutCopyMode = False
End Sub

When I press Debug, it highlights this line:

    sourceRange.Copy targetCell

If I un-hide the Sheet "ReportAsTable" and navigate to it, then run the code, it works without issue.

I tried adding a step to Activate the target Sheet before the Copy, with this:

    targetSheet.Range("A2").Select

but, it still throws the same error.


Solution

  • Thanks to everyone who took the time to offer suggestions. I'm not sure why this made it work, but it did and I wouldn't have gotten it without y'all.

    For some reason, Activating the target sheet, then back to the sheet that holds the buttons made it stop throwing the error. Here's what I ended up using:

        targetSheet.Visible = xlSheetVisible
        targetSheet.Activate
        ThisWorkbook.Sheets("Start Here").Activate
        sourceRange.Copy targetCell
        targetSheet.Visible = xlSheetHidden
    

    If anyone has any idea why that was needed, I'd love to learn from ya. Either way, I'm just glad it's working now.

    Thanks again!