我正在尝试将一张工作表(用户输入的)的全部内容复制到另一张工作表(隐藏但不受保护)。当我运行它时,出现错误:运行时错误'1004':Range类的复制方法失败。
这是我的代码:
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
当我按“调试”时,它会突出显示这一行:
sourceRange.Copy targetCell
如果我取消隐藏工作表“ReportAsTable”并导航到它,然后运行代码,它就可以正常工作。
我尝试在复制之前添加一个步骤来激活目标工作表,如下:
targetSheet.Range("A2").Select
但是,它仍然抛出相同的错误。
尝试使用这些行而不是激活目标表:
' Copy the data from the source range to the target cell
Sheets("ReportAsTable").Visible = xlSheetVisible
sourceRange.Copy targetCell
Sheets("ReportAsTable").Visible = xlSheetHidden