将启用宏的工作表从一个工作簿复制到另一个工作簿'运行时错误' 1004''

时间:2017-07-03 13:12:47

标签: excel vba excel-vba

我正在尝试创建一个宏,允许我将这个非常常用的工作表直接放入我们需要的文件中。它是一种常用的工作表,我喜欢快速和轻松插入现有文件,以便经常复制和使用。

我收到:运行时错误' 1004':Excel无法访问' Junk'。该文件可能是只读的或加密的。

此代码是从堆栈溢出的另一个解决方案修改的,以便在我希望的任何文档上全局使用。 (这是最终目标)以下代码:

Sub foo()
Dim x As Workbook
Dim y As Workbook
Dim z As String
z = ActiveWorkbook.Path

Dim WS As Worksheet
Sheets.Add.Name = "Finance"

'## Open both workbooks first:
Set x = Workbooks.Open("Desired worksheet file path")
Set y = Workbooks.Open(z)

'Now, copy what you want from x:
x.Sheets("Finance1").Range("A1:G12").Copy

'Now, paste to y worksheet:
y.Sheets("Finance").Range("A1:G12").PasteSpecial

'Close x:
x.Close

End Sub

在错误点,两个文件都打开了。

2 个答案:

答案 0 :(得分:1)

Thec代码就是这样。

Sub foo()
    Dim x As Workbook
    Dim y As Workbook
    Dim z As String, FileName1 As String, FileName2 As String

    z = ThisWorkbook.Path & "\"

    Dim WS As Worksheet
    FileName1 = "test1.xlsx"
    FileName1 = "test2.xlsx"
    '## Open both workbooks first:
    Set x = Workbooks.Open(z & FileName1)
    Set y = Workbooks.Open(z & FileName2)

    'Now, copy what you want from x:
    x.Sheets("Finance1").Range("A1:G12").Copy y.Sheets("Finance").Range("A1")

    x.Close

End Sub

答案 1 :(得分:1)

ActiveWorkbook.Path给出了activeworkbook的路径,你应该将文件添加到它。像这样:

Set y = Workbooks.Open(z & "\fileSample.xlsx")

还有一个错误选项 - 如果未保存ActiveWorkbook,则不会返回任何内容。因此,请检查它: If len(activeworkbook.path)>0 then