[英]Copying Macro-Enabled Worksheet from One Workbook to Another 'Run-time error '1004''
I am trying to make a macro that will allow me to drop this very commonly used worksheet directly into the files we need it in. It's a commonly used sheet that I'd like the ability to quickly and easily plop into existing documents to be copied and used frequently. 我正在尝试创建一个宏,使我可以将这个非常常用的工作表直接放入我们需要的文件中。这是一个常用的工作表,我希望能够快速,轻松地放入要复制的现有文档中并经常使用。
I am receiving: Run-time error '1004':Excel cannot access 'Junk'. 我收到:运行时错误'1004':Excel无法访问'垃圾'。 The document may be read-only or encrypted.
该文档可以是只读的或加密的。
This code is modified from another solution on stack overflow in order to be used globally on any document I wish. 此代码是从堆栈溢出的另一种解决方案修改而来的,以便在我希望的任何文档上全局使用。 (that's the end goal here) Code below:
(这是最终目标)下面的代码:
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
At the point of error both documents are open. 在错误点,两个文档都已打开。
Thec code would be like this. 该代码将是这样的。
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
ActiveWorkbook.Path
gives the path of the activeworkbook, you should add the file to it. ActiveWorkbook.Path
给出了activeworkbook的路径,您应该将文件添加到其中。 Like this: 像这样:
Set y = Workbooks.Open(z & "\\fileSample.xlsx")
There is one further options for an error - if the ActiveWorkbook is not saved, then it would not return anything. 还有一个错误选择-如果未保存ActiveWorkbook,则它将不返回任何内容。 Thus, check it like this:
If len(activeworkbook.path)>0 then
因此,以如下方式检查它:
If len(activeworkbook.path)>0 then
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.