0

(为我糟糕的英语提前道歉:不是第一语言:))我正在编写一个 VBA Excel 2003 例程,该例程在一个文件中运行 50 多个工作表,一个接一个地复制工作表(只是作为临时副本)然后执行操作在删除这些临时副本并返回其对工作表内容的计算结果之前对其进行处理。更准确地说:代码是从一个外部文件调用的,内部有一个(隐藏的)工作表。当我打开文件时,它会运行一个代码来在 Excel 中创建一个新工具栏,当我按下工具栏上的一个按钮时,我上面描述的代码就会运行。

我知道不保存文件并执行许多副本会触发此错误,但现在它在第一次尝试时触发(我已多次关闭并重新打开所有内容,以确保我没有保留未保存的情况)。

这是触发问题的代码,我很抱歉格式不好:

ActiveWorkbook.Worksheets("NAME OF THE FIRST WORKSHEET I WANT TO COPY").Copy ThisWorkbook.Worksheets("HiddenSheet")

Disclamer:工作表的名称由 For..Next 循环通过 ActiveWorkbook.Worksheets 数组找到,但即使我自己硬编码名称,代码也不起作用。

为了更清楚,这里有一大段代码:

Set sourceWorkbook = ActiveWorkbook
For index = 1 To sourceWorkbook.Worksheets.Count
    sourceWorkbook.Activate 'not sure if this is even needed
    Set currWorksheet = sourceWorkbook.Worksheets(index)
    currWorksheet.Copy ThisWorkbook.Worksheets("HiddenSheet")
Next index

结果现在始终如一:

运行时错误“1004”工作表类的复制方法失败。

我提前感谢大家的帮助!

4

1 回答 1

0

一些有用的指导方针:

Option Explicit
'Copy sheet
Sub CopySheet()

    Dim ws1 As Workbook, ws2 As Workbook

    'It's better to declare sheets and avoid activate
    Set ws1 = Workbooks("Book1")
    Set ws2 = Workbooks("Book2")

    'Copy sheet "Test" from ws1(Book1) to ws2 (Book2) after all sheets
    ws1.Worksheets("Test").Copy After:=ws2.Worksheets(Sheets.Count)

End Sub

Option Explicit
'Copy a range
Sub CopyRange()

    Dim ws1 As Workbook, ws2 As Workbook

    'It's better to declare sheets and avoid activate
    Set ws1 = Workbooks("Book1")
    Set ws2 = Workbooks("Book2")

    'Copy from ws1(Book1), sheet "Test" & range A1:A5 to ws2 (Book2), sheet "sheet1" & range A1
    ws1.Worksheets("Test").Range("A1:A5").Copy
    ws2.Worksheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteValues

End Sub
于 2019-06-20T13:47:58.860 回答